Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
本题主要考察对于sign integer逆序的考察,要注意的关键点有3个:
1.符号,对于负数可以先转换为正数来解决
2.溢出问题,要精行必要的判断
public class Solution {
public int reverse(int x) {
if(x==Integer.MIN_VALUE)
return 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;
}
}