Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
Analyze:
print ' ',bin(2147483647)
print ' ',bin(2147483646)
print ' ',bin(2147483648),'overflows'
print ' ',bin(-2147483647)
print ' ',bin(-2147483648),'overflows'
print ' ',bin(-2147483649),'overflows'
print ' ',bin(-2147483647)
0b1111111111111111111111111111111
0b1111111111111111111111111111110
0b10000000000000000000000000000000 overflows
-0b1111111111111111111111111111111
-0b10000000000000000000000000000000 overflows
-0b10000000000000000000000000000001 overflows
-0b1111111111111111111111111111111
Code 1 :
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x==0:
return x
flag=1
if x<0:
flag=-1
x=-x
re=0
i=1
while 1:
re=re+x%10
x=x/10
if x<1:
re=re*flag
break
re=re*10
i+=1
if re > 2147483647 or re < -2147483648:
return 0
return re
Submission Result:
Status: Accepted
Runtime: 64 ms
Ranking: beats 70.20%
Code 2:
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
if x==0:
return x
flag=1
if x<0:
flag=-1
x=-x
re=string.atoi(str(x)[::-1])
re=re*flag
if re > 2147483647 or re < -2147483648:
return 0
return re
Submission Result:
Status: Accepted
Runtime: 64 ms
Ranking: beats 70.20%
本文介绍了一种用于反转整数的算法实现,并通过两个不同的方法进行了展示。讨论了特殊情况的处理,如溢出情况及末位为0的情况,同时提供了LeetCode上的测试案例。
1499

被折叠的 条评论
为什么被折叠?



