题目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
一般来说整数的处理问题要注意的有两点,一点是符号,另一点是整数越界问题。
对于32位整数,1000000003 的翻转就是越界的。
public static int reverse(int x) {
if(x==Integer.MIN_VALUE)
return 0;
int num = Math.abs(x);
int res = 0;
while(num!=0)
{
if(res>(Integer.MAX_VALUE-num%10)/10)
return 0;
res = res*10+num%10;
num /= 10;
}
return x>0?res:-res;
}

本文介绍了如何实现整数翻转并处理32位整数越界的问题,包括符号判断与整数边界检查。
364

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



