[LeetCode]7.Reverse Integer ❤

来源:互联网 发布:mac下载os x yosemite 编辑:程序博客网 时间:2024/05/01 15:17

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.

____________________________ 以上摘自LeetCode题目

分析:大致思路就是简单的取每一位加权之后相加,有一点小难题在于如何判断溢出。

result > INT_MAX / 10

上面那句很好的解决了这个问题,避免了result>INT_MAX无法判断是否溢出的尴尬,若result>INT_MAX/10,那么下一个语句计算后result>INT_MAX恒成立;另外由于abs(INT_MIN)比INT_MAX大1,这种情况要单独判断。

代码如下

class Solution {public:    int reverse(int x) {        if (x == 0) return 0;         if (x == INT_MIN) return 0;        int t = abs(x);        int result = 0;        while (t > 0) {            if (result > INT_MAX / 10) return 0;            result = result*10 + t%10;            //cout << "result = " << result << endl;            t /= 10;        }        result += t;        if (x < 0) result = -1 * result;        return result;    }};