您的位置:首页 > 其它

【LeetCode】7. Reverse Integer

2018-03-26 11:26 513 查看
Given a 32-bit signed integer, reverse digits of an integer.Example 1:Input: 123
Output: 321
Example 2:Input: -123
Output: -321
Example 3:Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解法一:
注意数据范围是-2^32 ~ 2^32 - 1, Integer.MIN_VALUE ~ Integer.MAX_VALUE
代码如下:public int reverse(int x) {

long res = 0;
while (x != 0){
res = res * 10 + x % 10;
x /= 10;
}
return (res < Integer.MIN_VALUE || res > Integer.MAX_VALUE) ? 0 : (int) res;
}

解法二:
方法一样,但是不用定义long。If overflow exists, the new result will not equal previous one. (来源于LeetCode discussion)
代码如下:public int reverse(int x){
int result = 0;
while (x != 0){
int newResult = result * 10 + x % 10;
if ((newResult - x % 10) / 10 != result){
return 0;
}
result = newResult;
x = x / 10;
}
return result;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: