問題描述:
給定一個整數,請將該數各個位上數字反轉得到一個新數,
新數也應滿足整數的常見形式,即除非給定的原數為零,否則反轉后得到的新數的最高位數字不應為零,
輸入格式:
輸入共1行,1個整數N,
輸出格式:
輸出共1行,1個整數表示反轉后的新數,
資料范圍
∣ N ∣ ≤ 1 0 9 |N|≤10^9 ∣N∣≤109
輸入樣例:
123
輸出樣例:
321
輸入樣例:
-380
輸出樣例:
-83
演算法
(數學) O ( ) O() O();
思路:
巧用數學運算式res = res * 10 + n %10; 就是將最后一位取出,然后每次擴大10倍,此運算式也可以用于負數的情況,
時間復雜度分析
原題鏈接
C++代碼:
#include <iostream>
#include <cmath>
using namespace std;
int n;
int main()
{
cin >> n;
int res = 0;
while(n)
{
res = res * 10 + n % 10;
n /= 10;
}
cout << res << endl;
}
Java代碼:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.next().replaceAll("0+$", ""); //除去數字后面的0
int n = Integer.parseInt(str);
if (str.charAt(0) == '-') {
System.out.print('-');
for (int i = 1; i < str.length(); i++) {
System.out.print(str.charAt(str.length() - i));
}
} else {
for (int i = 1; i <= str.length(); i++) {
System.out.print(str.charAt(str.length() - i));
}
}
}
}
注:int 十進制:-2^31=-21 4748 3648 到 2^31-1=21 4748 3647,共10位,21億,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/260144.html
標籤:其他
