链接:
https://leetcode-cn.com/problems/reverse-integer/
题目:
给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。示例 1: 输入: 123 输出: 321
示例 2: 输入: -123 输出: -321
示例 3: 输入: 120 输出: 21
我的解法:
class Solution(object):
def reverse(self, x):
num = abs(x)
reverse_num = 0
while num != 0:
reverse_num = reverse_num * 10 + num % 10
num /= 10
reverse_num = reverse_num if x>0 else -reverse_num
return reverse_num if -2**31<=reverse_num<=2**31-1 else 0
我的解法2: 字符串
class Solution(object):
def reverse(self, x):
num = abs(x)
reverse_num = int(str(num)[::-1])
reverse_num = reverse_num if x>0 else -reverse_num
return reverse_num if -2**31<=reverse_num<=2**31-1 else 0