[Leetcode] 7. Reverse Integer

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值