【LeetCode with Python】 Reverse Integer

博客域名: http://www.xnerv.wang
原题页面: https://oj.leetcode.com/problems/reverse-integer/
题目类型:数值计算
难度评价:★★★
本文地址: http://blog.csdn.net/nerv3x3/article/details/3465557

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.


“反转”一个数字。主要注意负数的处理。数值计算类面试题有一个经常会被忽略的重要点,就是数值溢出。这里是用Python解题,所以对于int型的输入参数处理还不会有问题。但是如果是C++,result最好声明为long long的,以前本人做Rakuten的一道笔试题就是在这里栽了跟头。
所以最好还是用C++来做一次,充分考虑数据溢出的情况。

class Solution:
    # @return an integer
    def reverse(self, x):
        if x >= 0:
            leave = x
            sign = 1
        else:
            leave = -x
            sign = -1

        result = 0
        while 0 != leave:
            result = result * 10 + leave % 10
            leave /= 10
        return result * sign

你可能感兴趣的:(LeetCode,with,Python,LeetCode,with,Python,LeetCode,Python,LeetCode,with,Python)