Problem:
Reverse digits of an integer.
Example1: x = 123, return 321 Example2: x = -123, return -321
click to show spoilers.
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.
Update (2014-11-10): Test cases had been added to test the overflow behavior.
思路:
考虑几个情况
1. 整数的末尾是0,比如10,1000等
2. 假如输入的是32位整形,输入的原数没有越界,但是其反转整数则越界了。如2147483639和9363847412.
3. 对于以上问题,如果整形越界则函数返回0.
第一个情况用除法和取余就能容易解决了。第二种情况,由于python的整形不会越界,所以只需要加一个判断就好了;如果是C++,可以用try…throw方法使得越界时函数返回0。另外不要判断原来整数的符号。
Solution:
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 18 10:40:45 2017
@author: liangsht
"""
class Solution(object):
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
posFlag = True if x >= 0 else False
x = x if x >= 0 else -x
result = 0
while x != 0:
tmp = x % 10
#try:
result = result * 10 + tmp
x = x / 10
#except Exception,e:
# print e
# return 0
result = result if posFlag else -result
result = 0 if result > 2147483647 or result < -2147483648 else result
return result