1 |
Given a 32-bit signed integer, reverse digits of an integer. |
思路
异常情况
需要考虑到的特殊情况
- 输入的数正常,逆序后大于
int
的最大范围 - 最后一位为0 逆序后第一位要去掉
代码
使用
long
保存中间的运行结果
在最后与Integer.MAX_VALUE
&Integer .MIN_VALUE
进行比较1
2
3
4
5
6
7
8
9
10class Solution {
public int reverse(int x) {
long result = 0;
while(x != 0){
result = result * 10 + x % 10;
x = x / 10;
}
return result > (double)Integer.MAX_VALUE || result < (double)Integer .MIN_VALUE ? 0 : (int)result;
}
}
近期评论