Sunday, February 24, 2013

[LeetCode] Reverse Integer

Thought:
If a positive number reverse to a negative one, it means overflow in my opinion.
Zero is a special number that none of the integer's reverse is zero, so I chose it as the flag of overflow.

Code:
public class Solution {
    public int reverse(int x) {
        boolean isNegative = false;
        if( x < 0) {
            isNegative = true;
            x = -x;       
        }
       
        int result = 0;
        while( x / 10 != 0 ){
            int LSB = x % 10;
            x = x / 10;
            result = result * 10 + LSB;
        }
        result = result * 10 + x;
       
        if( result < 0 ){//overflow
            return 0;
        }
       
        if( isNegative ){
            return -result;
        }else{
            return result;
        }
    }
}

No comments:

Post a Comment