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.
这道题其实并不难,主要是需要考虑到溢出的问题,我提交的时候没有考虑到这个问题,因此参考了官网给出的解答方案,在这里做一小结。
因为整数的范围在-2147483648~2147483647之间,所以需要判断ret有没有越界,因为需要对ret进行乘10的操作,如果这时ret大于整型的最大值除以10,那么必然ret越界,如果这时ret等于整型的最大值除以10,还需判断加上的那一位是否大于7,如果大于7则越界;同样的,对于ret为负数的时候也同样需要判断。
还有,这里也并没有判断是正数还是负数,因为不管正负,对其进行取模和除的操作时,并不改变其正负。
以下是正确代码:
class Solution {
public int reverse(int x) {
int ret = 0;
while(x!=0){
int mod = x%10;
x = x/10;
//-2147483648~2147483647
if(ret>Integer.MAX_VALUE/10 || (ret==Integer.MAX_VALUE/10 && mod>7)) return 0;
if(ret<Integer.MIN_VALUE/10 || (ret==Integer.MIN_VALUE/10 && mod<-8)) return 0;
ret = ret*10 + mod;
}
return ret;
}
}