python3基础,将数字倒置(321转换为123、120转换为21 、 -1234转换为-4321 ),并添加测试用例
"""
Filename: solution.py
Created on Thu Mar 28 11:06:08 CST 2019
将321转换为123、 120转换为21 、 -1234转换为-4321 ,数值介于-2**31和2**31-1否则结果为0
"""
# 方法一
class Solution1:
def reverse(self, x: int) -> int:
# 算法写在这里
# ret = 0
# 先将其用绝对值转换成字符串并转置成列表
step_1 = list(reversed(str(abs(x))))
# 判断x是正值还是负值
if x >= 0:
ret = int(''.join(step_1))
else:
ret = int('-' + str(int(''.join(step_1))))
if ret > pow(2, 31)-1 or ret < -pow(2, 31):
return 0
return ret
# 方法二
class Solution2:
def reverse(self, x: int) -> int:
# 算法写在这里
# ret = 0
# 先取正
x_ = abs(x)
length = len(str(x_))
# 存结果
lis = []
for i in range(length):
# 取出每一位的值
step_1 = str(x_ // 10 ** i % 10)
lis.append(step_1)
if x >=0:
ret = int(''.join(lis))
else:
ret = int(('-' + str(int(''.join(lis)))))
if ret > pow(2, 31)-1 or ret < -pow(2, 31):
return 0
return ret
# 方法三
class Solution3:
def reverse(self, x: int) -> int:
# 算法写在这里
ret = 0
# 或者 step_1 = x if x > 0 else -x
step_1 = abs(x)
while step_1 != 0:
# 0*10 >> 0 乘
# 123%10 >> 3 取余
# 0+3 >> 0 相加
# 123//10 >> 12 整除
# 3*10 >> 30
# 12%10 >> 2
# 30+2 >> 32
# 12//10 >> 1
# 32*10 >> 320
# 1%10 >> 1
# 320+1 >> 321
# 1//10 >> 0
ret *= 10
ret += step_1%10
step_1 = step_1 // 10
ret = ret if x > 0 else -ret
if ret > pow(2, 31)-1 or ret < -pow(2, 31):
return 0
return ret
# 方法四
class Solution4:
def reverse(self, x: int) -> int:
rev = str(abs(x))[::-1]
sign = '' if x > 0 else '-'
ret = int(''.join([sign, rev]))
if ret > pow(2, 31)-1 or ret < -pow(2, 31):
return 0
return ret
# ===============================================================================
# Test
# ===============================================================================
test = {
123: 321,
-123: -321,
120: 21,
0: 0,
-100: -1,
1534236469: 0,
}
sol = Solution4()
for k, v in test.items():
res = sol.reverse(k)
print('-' * 80)
print('Input:', k)
print('Correct:', v)
print('Output:', res)
if res == v:
print('Passed>>>^_^')
else:
print('ERROR:Wrong!!')
执行结果: