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.
解答:
难点在正负与溢出(INT_MIN~INT_MAX)判断。对于c++,负数除法取余与前数相同,python则与后数相同。相应的取整也会有差异:r=a-n*[a/n],r是余数,a是被除数,n是除数。此次C++的语法更符合人类习惯,即-123%10=-3,-123/10=-12。
对于越界,有解法才用long long (64位)保存临时变量,再判断溢出,不符合题目要求。正确判断方式如下:
class Solution {
public:
int reverse(int n) {
int ret = 0;
int temp = 0;
while(n!=0)
{
temp = ret*10 + n%10;
if(temp/10 != ret) return 0;
ret = temp;
n = n/10;
}
return ret;
}
};