Reverse Integer

LeetCode #7


Description:

Reverse digits of an integer.

Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

Example:

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

Idea:

if(abs(result)>INT_MAX/10 )  // overflow
    return 0;
result = result*10 + x%10;
x /= 10;

这种情况不像String to Integer的情况,还要check if(num>maxDiv10 || (num==maxDiv10&&digit>=8) ) // Take care of the overflow case

原来的integer的开头不可能是>8的,在num==maxDiv10的情况下。

Code:

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

        while(x != 0){
            if(abs(result)>INT_MAX/10 )
                return 0;
            result = result*10 + x%10;
            x /= 10;
        }
        return result;

    }
};

results matching ""

    No results matching ""