给定一个 32 位有符号整数,将整数中的数字进行反转。
示例 1:
输入: 123 输出: 321
示例 2:
输入: -123 输出: -321
示例 3:
输入: 120 输出: 21
public class Reverse {
public static void main(String[] args) {
int a = reverse(1534232469);
System.out.println(a);
}
public static int reverse(int x) {
long result = 0l;
if(x >= 0) {
while(x != 0) {
result = result * 10 + x % 10;
x /= 10;
}
if(result > (Math.pow(2, 31) - 1) || result < (-Math.pow(2, 31))) {
return 0;
}else {
return (int)result;
}
}
else if(x < 0){
x = -x;
while(x != 0) {
result = result * 10 + x % 10;
x /= 10;
}
if(result > (Math.pow(2, 31) - 1) || result < (-Math.pow(2, 31))) {
return 0;
}else {
return -(int)result;
}
}
return (int)-result;
}
}
/*
分析:
1、32位数的范围是-2^31到2^31-1
2、如何解决溢出问题?
如32位数的范围是-2 147 483 648到2 147 483 647,如果输入的是1 333 333 333,反转以后结果就会溢出了。所以,刚开始,我们定义result的时候定义为long型的,如果反转之后有溢出,则输出为0.如果反转之后没有溢出,则再强制转回int型。
*/
如4321反转的过程:
1
12
123
1234
就是
result = result * 10 + x % 10
x /= 10