导航

LeetCode 7. Reverse Integer

Posted on 2016-09-20 19:55  CSU蛋李  阅读(101)  评论(0编辑  收藏  举报

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.

 

看完提示的难点,做起来就很容易了,主要是越界后我们要返回0

class Solution {
public:
    int reverse(int x) {
        unsigned long long result=0;
        if (INT_MIN == x||0==x)return 0;
        bool plus_or_minus_tag = true;
        if (x < 0)
        {
            x = -x;
            plus_or_minus_tag = false;
        }
        while (x)
        {
            result = result * 10 + x % 10;
            x /= 10;
        }
        if (plus_or_minus_tag)
        {
            if (result > 2147483647)
                return 0;
            else return int(result);
        }
        else
        {
            if (result > 2147483647)
                return 0;
            else return 0 - int(result);
        }
    }
};