classSolution: defreverse(self, x: int) -> int: ans = 0 flag = 0if x > 0else1 x = abs(x) while x != 0: ans = ans * 10 + x % 10 x = x // 10 if flag: ans = -ans
if x < -2 ** 31or x > 2 ** 31 - 1or ans < -2 ** 31or ans > 2 ** 31 - 1: return0 return ans
时间复杂度:$O(log(x))$。
空间复杂度:$O(1)$。
2.2 解法二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
# 这个方法要快一点,有时候会快很多(看 LeetCode 心情) classSolution2: defreverse(self, x: int) -> int: if x >= 2 ** 31 - 1or x <= -2 ** 31: return0 else: strg = str(x) if x >= 0: ans = strg[::-1] else: temp = strg[1:] temp2 = temp[::-1] ans = "-" + temp2 ifint(ans) >= 2 ** 31 - 1orint(ans) <= -2 ** 31: return0 else: returnint(ans)
classSolution: defreverse(self, x: int) -> int: ans = 0 flag = 0if x > 0else1 x = abs(x) while x != 0: ans = ans * 10 + x % 10 x = x // 10 if flag: ans = -ans
if x < -2 ** 31or x > 2 ** 31 - 1or ans < -2 ** 31or ans > 2 ** 31 - 1: return0 return ans
# 这个方法要快一点,有时候会快很多(看 LeetCode 心情) classSolution2: defreverse(self, x: int) -> int: if x >= 2 ** 31 - 1or x <= -2 ** 31: return0 else: strg = str(x) if x >= 0: ans = strg[::-1] else: temp = strg[1:] temp2 = temp[::-1] ans = "-" + temp2 ifint(ans) >= 2 ** 31 - 1orint(ans) <= -2 ** 31: return0 else: returnint(ans)
if __name__ == '__main__': solution = Solution() x = 1534236469 ans = solution.reverse(x) print(ans) print(-123 % 10)