[lintcode easy]Reverse Integer

Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer).

Example

Given x = 123, return 321

Given x = -123, return -321

 

\\\The length of Int data is from -2^31 to 2^31-1; [-2^31 , 2^31 -1] 即 [-2147483648,2147483647]

\\\In Java, using Integer.MAX_VALUE and Integer.MIN_VALUE to record the maximum length and minimum length of int.

\\\In C#, using int.MaxValue  and int.MinValue

\\\ use a long type to record result, then compare it to the max or min value, if it exceed, return 0;

 

public class Solution {
    /**
     * @param n the integer to be reversed
     * @return the reversed integer
     */
    public int reverseInteger(int n) {
        // Write your code here
        long res=0;
        
        while(n!=0)
        {
            int digit=n%10;
            res=res*10+digit;
            
            if(res>Integer.MAX_VALUE  || res<Integer.MIN_VALUE)
            {
                return 0;
            }
            n=n/10;
        }
        
        return (int)res;
    }
}

 

posted on 2015-12-01 02:27  一心一念  阅读(135)  评论(0编辑  收藏  举报

导航