Friday, May 30, 2014

Reverse Integer

public class Solution {
    public int reverse(int x) {
        //  Actually, for overflow cases, what we need is a long integer. Or check the result whether it is larger than Integer.MAX_VALUE. I didnt check this case, because test cases should result in a "long" value, while this function needs a int return
        if(Math.abs(x) < 10) return x;
        boolean negativeFlag = false;
        if (x <0) {
            negativeFlag = true;
            x = -1*x;// one interesting thing is that if I pass Integer.MIN_VALUE in, x = -1 * x is the same value
        }
        // Solution 1 -- could be considered as "cheating", using String instead.
        // String origin = Integer.toString(x);
        // StringBuffer sb = new StringBuffer();
        // int i = 0;
        // while(i < origin.length()){
        //     sb.append(origin.charAt(i));
        //     i++;
        // }
        // sb = sb.reverse();
        // int result = Integer.valueOf(sb.toString());
        // if (negativeFlag) result*=-1;
        // return result;
     
        // Solution 2
     
        long result;
        int xCopy = x/10;
        int remainder = x%10;
        result = remainder ;
        while(xCopy >= 10){
            remainder = xCopy%10;
            xCopy = xCopy/10;
            result = result * 10 + remainder;
        }
        result = result * 10 + xCopy;
        if (negativeFlag) result*=-1;
        return (int)result;
    }
    // Both solutions are accepted by LeetCode
}

No comments:

Post a Comment