题目:
Given a signed 32-bit integer x
, return x
with its digits reversed. If reversing x
causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1]
, then return 0
.
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
Example 1:
Input: x = 123 Output: 321
Example 2:
Input: x = -123 Output: -321
Example 3:
Input: x = 120 Output: 21
Example 4:
Input: x = 0 Output: 0
Constraints:
-231 <= x <= 231 - 1
思路:
首先因为进来的数字可能比较大,可能超过int,因此难点就在于判断给定数字是否落在需要反转的范围。这里采用的是提前和INT_MIN/10以及INT_MAX/10来相比较,如果超出范围就返回0。如果需要进行逆反,则直接按位取值反转即可。
代码:
class Solution {
public:
int reverse(int x) {
int ans = 0;
while (x) {
if (ans < INT_MIN / 10 || ans > INT_MAX / 10) {
return 0;
}
int rest = x % 10;
x /= 10;
ans = ans * 10 + rest;
}
return ans;
}
};