Desciption:
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 store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Explantation:
題意如標題。
Note: 考慮overflow問題 超過range 則 return 0
Language: python
import math
def is_number(s):
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
max = math.pow(2,31) - 1
min = (math.pow(2,31))*(-1)
print "min:" , min
print "MAX:",int(max)
print "x=",x
print(type(x))
flag = 0
if x < 0 :
x = -x
flag = 1
tmp = x
ans = []
flag2 = 0
while tmp!=0 :
if (tmp%10 or flag2==1) !=0 :
ans.append(tmp%10)
flag2 = 1
tmp = tmp / 10
print(ans)
final_ans = ""
for i in range(len(ans)):
if is_number(ans[i]):
final_ans+=str(ans[i])
print "check: ",final_ans
#print "test:",float(final_ans)
if x == 0:
return "0"
elif (int(final_ans)*(-1)) < min:
return "0"
elif flag == 1:
return "-"+final_ans
elif x == 0 :
return "0"
elif int(final_ans) > max:
return "0"
#elif int(final_ans) < min:
# return 0
else:
return final_ans
Submitted Code: 6 months ago