首页 > 其他 > 详细

[lintcode easy]Reverse Integer

时间:2015-12-01 07:06:00      阅读:326      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

[lintcode easy]Reverse Integer

原文:http://www.cnblogs.com/kittyamin/p/5008987.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!