Description:
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
这是一道基本的对数字操作的题,除却简单外还需要注重细节,这道题就是注意 Integer的溢出问题。
1. 功能的实现: result = result * 10 + x % 10;
2. 溢出的检测:
a) The absolute value of Integer's minimum is larger 1 than Integer's maximum.
To the final answer, we need to judge its plus-minus.
For example,
return x?result:-result;
b) Even if the value of x is less than the Integer's maximum, its reverse value will be larger than that.
We can judge it in the loop.
For example,
if (Math.abs(result) > Integer.MAX_VALUE / 10)
or
int t = res * 10 + x % 10;
if (t / 10 != res) return 0; // If the value has exceeded the limit, it divided by 10 will differ from before.
or a direct comparison
if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0;
So, the code should be:
class Solution {
public:
int reverse(int x) {
int res = 0;
while (x != 0) {
if (abs(res) > INT_MAX / 10) return 0;
res = res * 10 + x % 10;
x /= 10;
}
return res;
}
};
class Solution {
public:
int reverse(int x) {
int res = 0;
while (x != 0) {
int t = res * 10 + x % 10;
if (t / 10 != res) return 0;
res = t;
x /= 10;
}
return res;
}
};
An easier implementation:
class Solution {
public int reverse(int x) {
long res = 0; // ***When res use the long type, it will keep the value to check whether it exceed the limit.
while(x != 0) {
int tail = x % 10;
res = res * 10 + tail;
if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) {
return 0;
}
x = x / 10;
}
return (int) res; // ***Return int type.
}
}
Lesson learned:
1.Overflow
2.Difference between Integer's maximum and minimum
3. How to check the overflow
4. A FUNCTION: (condition) ? result1 : result2