LeetCode(7. Reverse Integer)
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
**Note:
**The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
知識點:
- 這道題考察了關于C++ int類型的范圍以及存儲方式。這就要了解數字是如何在計算機存儲的了,這涉及到原碼,反碼和補碼的知識。關于這方面的內容,我推薦一篇講得非常清楚的博客:C++原碼,反碼,補碼詳解
不過在實際使用中,我們只需要知道C++ int 的范圍位于-232 --- 232-1, 且我們可以用INT_MAX表示int的最大值,用INT_MIN表示int的最小值。 - 關于一個數值是否越界的判斷:這里我用到了這樣一個小tip,即如果有可能 a + b > INT_MAX的話,為了防止越界造成的麻煩,我們用 a > INT_MAX - b 來判斷。其他的運算同理(比如乘法轉除法)。這樣的等價判斷避免了越界帶來的麻煩。
解題思路:
這里要注意先判斷x是否為INT_MIN,如果是的話,直接返回0,因為INT_MIN的反向數值是越界的;如果不是的話,這樣我們就可以把x取絕對值而不用擔心取絕對值后x的越界問題,便于我們對數字進行處理。
接下來就是對原來的數字一位一位的取反了,要注意的是在進行到最后一位的時候,要進行越界判斷了。此時只要用到我們上面講到的小tip就可以了。
最后的返回值別忘了正負號就好了。
C++代碼如下:
class Solution {
public:
int reverse(int x) {
if (x == INT_MIN)
return 0;
int ans = 0;
bool flag = x<0? true:false;
for (x=flag? -x:x; x>=10; x/=10){
ans = ans*10 + x%10;
}
//check if out of bounds
if (!flag){// positive number
if (INT_MAX / 10 < ans)
return 0;
if (INT_MAX - ans*10 < x)
return 0;
}
else{//negative number
if (-(INT_MIN / 10) < ans)
return 0;
if (INT_MIN + ans*10 > -x )
return 0;
}
//positive or negative process
if (!flag){
ans = ans*10 + x;
return ans;
}
else{
ans = -ans*10 - x;
return ans;
}
}
};