LeetCode 7. Reverse Integer
Description
Given a 32-bit signed integer, reverse digits of an integer.
Example
Code
- java
class Solution {
public int reverse(int x) {
long temp = x, result = 0;
boolean neg = x < 0 ? true : false;
if(neg) temp = -temp;
while(temp != 0) {
result = result * 10 + temp % 10;
temp /= 10;
}
long minValue = Integer.MAX_VALUE, maxValue = Integer.MAX_VALUE;
minValue += 1;
if((neg && result > minValue) || (!neg && result > maxValue)) return 0;
if(neg) result = -result;
return (int) result;
}
}
- Official Solution
class Solution {
public int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0;
if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0;
rev = rev * 10 + pop;
}
return rev;
}
}
Conclusion
- 要特别注意边界情况,特别是负数