Saturday, June 27, 2015

Reverse Integer

Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).
Have you met this question in a real interview?
Yes
Example
Given x = 123, return 321
Given x = -123, return -321
Tags Expand  
public class Solution {
    /**
     * @param n the integer to be reversed
     * @return the reversed integer
     */
    public int reverseInteger(int n) {
        // Write your code here
        if(n == 0) return n;
        int sign = 1;
        if(n < 0){
            sign = -1;
            n = -n;
        }
       
        int result = 0;
        while(n > 0){
            if(Integer.MAX_VALUE/ 10 < result || (Integer.MAX_VALUE - n % 10) / 10 < result) return 0;
            result = result * 10 + n % 10;
            n /= 10;
        }
        return result * sign;
    }
}

No comments:

Post a Comment