题目链接
文章目录
Python3
官方解法 ⟮ O ( ∣ x ∣ ) 、 O ( 1 ) ⟯ \lgroup O(|x|)、O(1)\rgroup ⟮O(∣x∣)、O(1)⟯
class Solution:
def reverse(self, x: int) -> int:
INT_MIN, INT_MAX = -2**31, 2**31 - 1
rev = 0
while x != 0:
if rev < INT_MIN // 10 + 1 or rev > INT_MAX // 10:
return 0
digit = x % 10
if x < 0 and digit > 0:
digit -= 10 # Python3 的取模运算在 x 为负数时也会返回 [0, 9) 以内的结果,因此这里需要进行特殊判断
x = (x - digit) // 10
rev = rev * 10 + digit
return rev
写法2
class Solution:
def reverse(self, x: int) -> int:
flag = 1
if x < 0:
flag = -1
x = - x
res = int(str(x)[::-1])
#return 0 if (res > 2**31 - 1 or -res < -2**31) else res * flag
return res * flag if -2**31<= res <= 2**31 - 1 else 0
class Solution:
def reverse(self, x: int) -> int:
flag = 1
if x < 0:
flag = -1
x = - x
s = str(x)
res = ''
for i in range(len(s)-1, -1, -1):
res += s[i]
res = int(''.join(res))
return 0 if (res > 2**31 - 1 or -res < -2**31) else res * flag
写法3
class Solution:
def reverse(self, x: int) -> int:
flag = 1
if x < 0:
flag = -1
x = - x
res = 0
while x > 0:
x, tmp = divmod(x, 10)
res = res * 10 + tmp
res *= flag
if -2**31 <= res <= 2**31 - 1:
return res
else:
return 0
C++
官方解法 ⟮ O ( ∣ x ∣ ) 、 O ( 1 ) ⟯ \lgroup O(|x|)、O(1)\rgroup ⟮O(∣x∣)、O(1)⟯
class Solution {
public:
int reverse(int x) {
int res = 0;
//int INT_MAX = 2**31-1; INT_MIN = -2**31; // C++ 自带
while (x != 0){
if (res < INT_MIN / 10 || res > INT_MAX / 10){// 注意写法
return 0;
}
int digit = x % 10;
x /= 10;
res = res * 10 + digit;
}
return res;
}
};