LeetCode - 7. Reverse Integer
Posted 朝研行歌
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode - 7. Reverse Integer相关的知识,希望对你有一定的参考价值。
Discription
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer‘s last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Difficulty:★
Solving Strategy
- 32 位有符号整数的取值范围:-2147483648 ~ 2147483647
- 如果输入整数为0,则直接返回0
- 设置判断正负数的flag
- 将输入整数转换为string,使用队列数据结构,依次弹出队首元素,根据十进制按位累加,最后进行溢出判断
My Solution
1 # 7 reverse 2 """ 3 Reverse digits of an integer. 4 5 Example1: x = 123, return 321 6 Example2: x = -123, return -321 7 8 """ 9 class Solution(object): 10 def reverse(self, x): 11 """ 12 :type x: int 13 :rtype: int 14 """ 15 if x == 0: 16 return 0 17 18 is_neg = False 19 if x < 0: 20 is_neg = True 21 x = abs(x) 22 23 aStack = [] 24 for i in str(x): 25 aStack.append(i) 26 27 bStack = aStack[:] 28 sum = 0 29 base = 1 30 while bStack: 31 index = bStack.pop(0) 32 sum = sum + int(index) * base 33 base = base * 10 34 35 if 2147483648 < sum: 36 return 0 37 elif 2147483648 == sum and is_neg == False: 38 return 0 39 elif is_neg: 40 return -sum 41 42 return sum
Runtime: 69 ms
Other Solution
Get the sign, get the reversed absolute integer, and return their product if r didn‘t "overflow".1 def reverse(self, x): 2 # sign = cmp(x, 0) # The cmp() function had be gone in python3 3 sign = (x > 0) - (x < 0) 4 re_num = int(str(sign * x)[::-1]) 5 return sign * re_num * (re_num < 2**31)
以上是关于LeetCode - 7. Reverse Integer的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 7. 整数反转 Reverse Integer
LeetCode 7. 整数反转 Reverse Integer
Leetcode 7. Reverse Integer(python)