Wednesday, March 4, 2015

Reverse integer

I don't remember how many times I have solved this problem, but somehow I can never remember the exact way to solve the problem.

Basically, after dealing with the negative number issue, mod x by 10, add it to the result number, which is the result number in the previous loop * 10.

Do remember to take care of the overflow problem.


public int reverse(int x) {
        if(x > -10 && x < 10)
            return x;
        boolean isNegative = false;
        if(x < 0){
            isNegative = true;
            x = -x;
        }
        long num = 0;
        while(x > 0){
            num = num * 10l + (long)x % 10l;
            if(num > Integer.MAX_VALUE)
                return 0;
            x /= 10;
        }
        return isNegative ? -(int)num : (int)num;
    }

No comments:

Post a Comment