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: [−23 1 , 23−1] . For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows
题目大意:
32位有符号int型整数,将它反转。
解题思路:
思路比较多,主要的问题在于有的转换后会溢出超过int可表示的范围。第一个思路可以转成string再用stoi转换成int型;第二个思路是直接利用除法和余数将每一位的数字分离出来,分离出来的数字乘以10再加上下一个分离出来的数字,直到原来传入的数字变为0。
P.S.这道题WA了几次,主要是没有注意到int范围,当溢出时要记得返回0.
解题代码:
class Solution {
public:
int reverse(int x) {
int rev = 0;
while (x != 0) {
int pop = x % 10;
x /= 10;
if (rev > INT_MAX / 10 || (rev == INT_MAX / 10 && pop > 7)) return 0;
//当x为正数时,如果x比INT_MAX大则返回0
if (rev < INT_MIN / 10 || (rev == INT_MIN / 10 && pop < -8)) return 0;
//当x为负数时,如果x比INT_MIN小则返回0
rev = rev * 10 + pop;
}
return rev;
}
};
网友评论