思路一:按照数学方法,取各位十位
思路二:将数字转为字符,再按照字符的反转规则取反
# 1. 将输入的看做一个数,分别从低到高取各位数字
# pop: x % 10
# push: temp = x % 10, num = num*10 + temp
# Runtime: 16 ms, faster than 85.39% of Python online submissions for Reverse Integer.
class Solution(object):
def reverse(self, x):
a = abs(x) # the absolute value of x
num = 0
while(a != 0):
#123
temp = a % 10
num = num*10 + temp
a = a // 10
if x > 0 and num < 2**31:
return num
elif x < 0 and num < 2**31:
return -num
else:
return 0
s = Solution()
s.reverse(1235)
5321
# 2. 将数字先转成字符,然后反转
# str[::-1] 取反
# Runtime: 16 ms, faster than 85.39% of Python online submissions for Reverse Integer.
class Solution(object):
def reverse(self, x):
if x<0:
ret=int("-"+str(-x)[::-1])
else:
ret=int(str(x)[::-1])
if (ret<-2**31 or ret>2**31-1):
ret=0
return ret
s = Solution()
s.reverse(1235)
5321
# 字符操作复习
str1 = 'abcdefg'
# 复制一遍全部字符
str1[:]
'abcdefg'
# 反转字符
str1[::-1]
'gfedcba'
# 反转且间隔为2得到新字符
str1[::-2]
'geca'
# 从首个去到倒数第一个
str1[:-1]
'abcdef'
# 从第二个取到最后一个
str1[1:]
'bcdefg'