7. Given a 32-bit signed integer, reverse digits of an integer.
Solution 1:
convert int into string, then reverse string by slice operator
def reverse(x):
"""
:type x: int
:rtype: int
"""
sign = 1 if x > 0 else -1
x = abs(x)
x = str(x)[::-1]
re = sign * int(x)
return re if -2**31 < re < 2**31 -1 else 0
- a[-1] -> last item in array
- a[s:] -> item starts at s (include s)
- a[+number:] -> item starts at that number
- a[-number:] -> last number items in array
- a[:p] -> item ends at p (not include p)
- a[:+number] -> item ends at that number
- a[:-number] -> all items except last that number in array
- a[:] -> copy whole array
- a[::-1] –> reverse all items in the array
Solution 2:
use stack to solve this problem
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
stack = []
sign = 1 if x >0 else -1
x = abs(x)
while x>0:
reminder = x % 10
x = x // 10
stack.append(reminder)
reverse = 0
for i in range(len(stack)):
reverse += stack[i] * (10**(len(stack)-1-i))
reverse = sign * reverse
return reverse if -2**31 < reverse <2**31-1 else 0
- use mod to get reminder, which is to push to stack
- get reversed number in stack and mulitply back to integer