[C++]LeetCode 7:Reverse Integer(翻转整数)

Problem:

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.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.


分析:

看似简单的逆序问题,最需要注意的是溢出。

解法一:转换为数组二分交换

解法二:直接使用x/10 ,x%10。(代码中方法)


下面主要关注的是溢出问题

首先需要了解的是最大整数和负数,在limits.h中有宏定义,如下:

#define INT_MAX 2147483647
#define INT_MIN (-INT_MAX - 1)
对于本题的乘法判断溢出的方法为:

//a*b是否溢出
a&&b != 0 && (INT_MAX / abs(a) < b
对于加法是否溢出:

//a+b是否溢出,注意a、b为非负整数
(unsigned int)a + (unsigned int)b > INT_MAX)

AC Code (C++):

class Solution {
public:
    //1032 / 1032 test cases passed.
    //Runtime: 15 ms

    #define INT_MAX 2147483647
    #define INT_MIN (-INT_MAX - 1)
    
    int reverse(int x) {
    	int flag = 1;//设置正负指示
    	if (x < 0){
    		flag = -1;
    		x = -x;
    	}
    
    	int num = 0;
    	while (x > 0){
    		if ((num != 0 && (INT_MAX / abs(num) < 10)) || ((unsigned int)abs(num * 10) + (unsigned int)(x % 10) > INT_MAX)){//溢出
    			return 0;
    		}
    		num = num * 10 + flag * (x % 10);
    		x = x / 10;
    	}
    
    	return num;
    }
};

测试用例:

被下组数据WA了好久,编代码的时候可以测试下:

1028 / 1032 test cases passed.

Input: 1534236469
Output: 1056389759
Expected: 0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值