您的位置:首页 > 编程语言 > C语言/C++

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

2015-05-02 14:23 585 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: