leetcode 7. Reverse Integer(C语言,翻转一个整数,判断是否溢出)19

贴原题:

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.

Note: The input is assumed to be a 32-bit signed integer. Your
function should return 0 when the reversed integer overflows.

解析:
  本题是要让翻转一个32位的整数,负数只翻转数值部分,符号位保持不变。
  我感觉这道题最难的点在于如何判断一个数翻转之后是否溢出。(这一点我一会在下面做个总结)

贴代码:

int reverse(int x) {
    int y=0;//需要返回的数
    while(x)
    {
        int temp=y;//暂存y的值
        y=y*10+x%10;//倒序;把x的最低位依次压入y的最低位
        if((y-x%10)/10!=temp)//反向推,若推不出原值则溢出
        {
            return 0;
        }
        x/=10;
    }
    return y;
}

总结:
  如何判断是否溢出?
  其实看我上面的代码也可以看得出了,只要把这个式子反着推过来,再来看是否相等就行了。

  1. 加法溢出判断:若c=a+b; c-a!=b则溢出;或者a, b>0, c<0溢出;或者a, b<0, c>0溢出;
  2. 减法溢出判断:若c=a-b; c+b!=a则溢出;
  3. 除法溢出判断:若b!=0 && a/b=c; b*c!=a则溢出
  4. 乘法溢出判断:若c=a*b; a!=0 && c/a!=b则溢出

      以上全为我个人总结,如有错误还请大家指出!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值