您的位置:首页 > 编程语言 > Python开发

【LeetCode with Python】 Reverse Integer

2008-12-07 13:05 513 查看
博客域名:http://www.xnerv.wang

原题页面:https://oj.leetcode.com/problems/reverse-integer/

题目类型:数值计算

难度评价:★★★

本文地址:/article/1377551.html

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: