Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

看似简单,但是要考虑到溢出判断的情况,C++代码如下:

class Solution {
public:
    int reverse(int x) {
    int reverse = 0;
    int MAX_INT = 0x7fffffff;

    while(x)
    {
        reverse = reverse * 10 + x % 10;
        x = x /10;
        if((reverse > 0 ? reverse : -reverse) > (MAX_INT / 10) && x)
        {
            return 0;
        }
    }

    return reverse;
    }
};

你可能感兴趣的:(Reverse Integer)