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

  1. 32 位有符号整数的取值范围:-2147483648 ~ 2147483647
  2. 如果输入整数为0,则直接返回0
  3. 设置判断正负数的flag
  4. 将输入整数转换为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

Short & nice solution in python
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)
 
posted @ 2016-03-14 11:39  朝研行歌  阅读(138)  评论(0编辑  收藏  举报