http://7371901.blog.51cto.com/user_index.php?action=addblog_new

http://fisherlei.blogspot.com/2012/12/leetcode-reverse-integer.html


public class Solution {
    public int reverse(int x) {
        
        // Solution A
        // return reverse_Mod(x);
        
        // Solution B
        return reverse_String(x);
    }
    
    ///////////////////
    // Solution A: Use %
    //
    private int reverse_Mod(int x)
    {
        long toReturn = 0;
        while (x != 0)
        {
            int lastDigit = x % 10;
            toReturn = toReturn * 10 + lastDigit;
            x = x / 10;
            
            if (toReturn > Integer.MAX_VALUE || toReturn < Integer.MIN_VALUE)
                return 0;   // Overflow
        }
        return (int)toReturn;
    }
    
    //////////////////
    // Solution B: Use String
    //
    private int reverse_String(int x) {
        
        // Int to String
        // Reverse
        // String to Long
        // Long to Int

        boolean negative = x < 0;
        String str = String.valueOf(x);
        if (negative)
            str = str.substring(1, str.length());

        String reversedStr = new StringBuilder(str).reverse().toString();
        Long thelong = Long.parseLong(reversedStr);

        if (thelong > Integer.MAX_VALUE)
            return 0;   // Overflow
            
        int toReturn = thelong.intValue();
        if (negative)
            toReturn = -toReturn;
        return toReturn;
    }
}