Leetcode:7- Reverse Integer
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
Input: 123
Output: 321
Example 2:
Input: -123
Output: -321
Example 3:
Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
题意:翻转整数
思路:需要注意两个问题。(1)翻转后前置0去掉(下述方法不会出现前导0) (2)超出32位int类型的时候输出0。这个范围在【-2147483648~2147483647】即-2^31 ~ 2^31-1
1 class Solution(object): 2 def reverse(self,x): 3 answer = 0 4 if x > 0: 5 sign = 1 6 else: 7 sign = -1 8 x = abs(x) 9 while x > 0: 10 answer = 10 * answer + x % 10 #取x的最后一位算到answer中 11 x //= 10 #去掉x的最后一位 12 if answer > 2147483648: #32位int类型的范围为【-2147483648~2147483647】 13 return 0 14 else: 15 return sign*answer 16 17 if __name__=='__main__': 18 solution = Solution() 19 x = 123 20 print(solution.reverse(x))

浙公网安备 33010602011771号