前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode: Reverse Integer

Leetcode: Reverse Integer

作者头像
卡尔曼和玻尔兹曼谁曼
发布2019-01-22 16:03:52
6120
发布2019-01-22 16:03:52
举报

题目: 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++代码:

代码语言:javascript
复制
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#代码:

代码语言:javascript
复制
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语言不通,所以要分正数和负数情况不同对待)

代码语言:javascript
复制
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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015年03月22日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档