題目鏈接
tag:
- easy
question:
??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: -2147483648~2147483647. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
C++ 解法:
思路:
??用long long型變量保存計算結(jié)果,最后返回的時候判斷是否在int返回內(nèi),代碼如下:
class Solution {
public:
int reverse(int x) {
// 數(shù)學(xué)分析不等式條件
int res = 0;
while (x != 0) {
if (res > INT_MAX / 10 || res < INT_MIN / 10) {
return 0;
}
int digit = x % 10;
x /= 10;
res = res*10 + digit;
}
return res;
}
};
class Solution {
public:
int reverse(int x) {
long long res = 0;
while (x != 0) {
res = res*10 + x % 10;
x /= 10;
}
return (res < INT_MIN || res > INT_MAX) ? 0 : res;
}
};
Python 解法:
??比較簡單,轉(zhuǎn)化為字符串反轉(zhuǎn)即可,見代碼:
class Solution:
def reverse(self, x: int) -> int:
res = int(str(abs(x))[::-1])
if res > 2**31-1:
return 0
if x < 0:
return -res
else:
return res