Leetcode: Reverse Integer

来源:互联网 发布:linux ping 测试 带宽 编辑:程序博客网 时间:2024/05/18 21:09

题目:
Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321
题目提示:
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.

分析:就是从后往前提取数字,然后相加,注意数字溢出问题就好了。
刚开始我写的时候,程序中还考虑了正负数的问题,后来发现程序直接写就OK,负号不影响最终结果。
C++代码:

class Solution{public:    int reverse(int x)    {        long long result = 0;        while (x)        {            result = result * 10 + x % 10;            if (result > INT_MAX || result < INT_MIN)            {                return 0;            }            x /= 10;        }        return (int)result;    }};

存在问题:当我将最大整数和最小整数写成数字的时候,即2147483647和-2147483648的时候,我在Leetcode下提交没问题,但是在Visual Studio2013中当x为负数的时候,运行结果为0,不知道为什么?读过一篇文章上面说不能写数字-2147483648要写成(-2147483647-1),是的INT_MIN就是这样定义的。但是为什么在Leetcode上的编译器能执行正确的结果呢?是不是由于编译器的问题。
还有在C#的Integer类中定义的MinValue直接写的是-2147483648而不是-2147483647-1,为什么在C#中可以直接使用-2147483648而在C++中就不行呢?

C#代码:

public class Solution{    public int Reverse(int x)    {        long result = 0;        while (x != 0)        {            result = result * 10 + x % 10;            if (result > int.MaxValue || result < int.MinValue)            {                return 0;            }            x /= 10;        }        return (int)result;    }}

Python参考代码:
(注意Python取余的方式和类C语言不通,所以要分正数和负数情况不同对待)

class Solution:    # @return an integer    def reverse(self, x):        result = 0        flag = 1        if x < 0:            x = x * -1            flag = -1        while x != 0:            result = result * 10 + x % 10            if result > 2147483647 or result < -2147483648:                return 0            x = x / 10        return result * flag
0 0
原创粉丝点击