题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Note:
The input is assumed to be a 32-bit signed integer. Your
function should return 0 when the reversed integer
overflows.
解法:
int start = 0;
if(x<0){
start = 1;
}
char [] test = String.valueOf(x).toCharArray();
int exp = 0;
int result = 0;
for(int i=start;i<test.length;i++){
result+=(test[i]-'0')*(Math.pow(10,exp));
exp++;
}
if(result>=Math.pow(2,31)-1){
return 0;
}
if(start==1){
result = result-result*2;
}
return result;
本文介绍了一种用于翻转32位带符号整数的算法,并提供了详细的Java代码实现。该算法首先判断输入整数是否为负数,然后通过遍历字符数组的方式逐位翻转数字,并使用数学运算确保翻转后的结果仍在32位整数范围内。
269

被折叠的 条评论
为什么被折叠?



