O(n)
class Solution:
def reverse(self, x: int) -> int:
if x == 0:
return 0
sign = '-' if x < 0 else ''
x = abs(x)
l = []
while x > 0:
l.append(str(x%10))
x = int(x/10)
y = int(sign+''.join(l))
if y < -2**31 or y > 2**31-1:
return 0
return y
def main():
s = Solution()
print(s.reverse(123)) # 321
print(s.reverse(-123)) # -321
print(s.reverse(120)) # 21
print(s.reverse(0)) # 0
if __name__ == '__main__':
main()
O(n)
class Solution:
def reverse(self, x: int) -> int:
if x == 0:
return 0
re = 0
if x > 0:
while x > 0:
re = re*10 + x%10
x = int(x/10)
else:
x = -1*x
while x > 0:
re = re*10 + x%10
x = int(x/10)
re = -1*re
if re < -2**31 or re > 2**31-1:
return 0
return re
def main():
s = Solution()
print(s.reverse(123)) # 321
print(s.reverse(-123)) # -321
print(s.reverse(120)) # 21
print(s.reverse(0)) # 0
if __name__ == '__main__':
main()
O(n)
class Solution:
def reverse(self, x: int) -> int:
if x >= 0:
re = int(str(x)[::-1])
else:
re = -1*int(str(-x)[::-1])
if re < -2**31 or re > 2**31-1:
return 0
return re
def main():
s = Solution()
print(s.reverse(123)) # 321
print(s.reverse(-123)) # -321
print(s.reverse(120)) # 21
print(s.reverse(0)) # 0
if __name__ == '__main__':
main()