LeetCode7. Reverse Integer

一、问题描述

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:
Input: 123
Output: 321

Example 2:
Input: -123
Output: -321

Example 3:
Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


二、思路及注意事项

  1. 注意最后的说明,如果超限,则返回0。
  2. 不需要考虑正负号的影响
  3. 注意特殊数字-2147483648 = -(2^31),取绝对值时会超限溢出。
  4. 查看以下示例中,判断数据是否溢出的方法
  5. 还是通过示例计算,查看数据计算规则
  6. 32位有符号整数的范围:-(2^31) ~ (2^31)-1
  7. 32位有符号整数中,负数比正数个数多1个。
  8. **32位无符号整数的范围:**0~(2^32)-1

三、程序示例(共4种方法)

C#版本

class Program
{
    //自己最开始写的。
    //不过超限溢出并没注意。
    //直到提交时当输入为-2147483648时,
    //报错后才发现题目的溢出提醒。
    //此处溢出判断参考官方给出的答案。
    public static int reverse1(int x)
    {
        int temp = x;
        int remain = 0;
        int reverse = 0;
        while (temp!=0)
        {
            remain = temp % 10;
            temp = temp / 10;
            //注意该判断,是否超限溢出
            if (Math.Abs(reverse) > int.MaxValue / 10)
            {
                return 0;
            }
            reverse = reverse * 10 + remain;
        }

        return reverse;
    }

    public static int reverse2(int x)
    {
        int res = 0;
        while (x != 0)
        {
            //官方给出的答案:注意该判断,是否超限溢出
            if (Math.Abs(res) > int.MaxValue / 10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }

    //通过高级数据类型,解决溢出问题
    public static int reverse3(int x)
    {
        long res = 0;
        while (x != 0) {
            res = 10 * res + x % 10;
            x /= 10;
        }
        return (res > int.MaxValue || res < int.MinValue) ? 0 : (int)res;
    }

    //溢出判断的另外一种方法
    public static int reverse4(int x)
    {
        int res = 0;
        while (x != 0)
        {
            int t = res * 10 + x % 10;
            if (t / 10 != res) return 0;
            res = t;
            x /= 10;
        }
        return res;
    }

    static void Main(string[] args)
    {
        //int num = 123;
        int num = -2147483648;
        int result = reverse4(num);
    }
}

感谢博主的分享。
http://www.cnblogs.com/grandyang/p/4125588.html


2018.03.16:更新有符号与无符号32位整数的范围。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值