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 store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
解法一
每个循环开始前判断res的值是否大于最大值/10,大于则直接返回0。
public int reverse(int x) {
int res=0;
while(x!=0)
{
if(Math.abs(res)>Integer.MAX_VALUE/10)
return 0;
res=res*10+x%10;
x=x/10;
}
return res;
}
Runtime: 13 ms, faster than 100.00% of Java online submissions for Reverse Integer.
Memory Usage: 37.9 MB, less than 59.07% of Java online submissions for Reverse Integer.
解法二
如果数值溢出了的话,那么它除以10的值和未乘10之前的值是不相等的。
public int reverse(int x) {
int res=0;
while(x!=0)
{
int tmp=res*10+x%10;
if(tmp/10!=res)
return 0;
res=tmp;
x=x/10;
}
return res;
}
Runtime: 14 ms, faster than 99.97% of Java online submissions for Reverse Integer.
Memory Usage: 38 MB, less than 15.74% of Java online submissions for Reverse Integer.
- 不能想得太复杂,此题的重点不是如何翻转,而是如何判断是否溢出。
- 需要注意的是为何不用判断翻转后的值是否等于214748364,因为若res=214748364,翻转前的数字也要符合范围,则只能是1463847412,而它翻转过来之后是没有溢出的。