标签:blog add 输入 obj append etc string logs net
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:★
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
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)
标签:blog add 输入 obj append etc string logs net
原文地址:http://www.cnblogs.com/gxcdream/p/7457487.html