LeetCode | Reverse Integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

若果不考虑边界溢出的话,只是简单的实现reverse功能:

 

public class Solution {
	public static int reverse(int x) {
		int num = Math.abs(x);
		int res = 0;
		
		while(num != 0){
			res = res*10 + num%10;
			num = num/10;
		}
		
		return x>0?res:-res;
	}
}


而实际要考虑Java中int的取值范围,加上边界溢出检测条件,提示当大于等于溢出边界时输出 0 

 

 

public class Solution {
    public int reverse(int x) {
        if(x == Integer.MIN_VALUE) return 0;  //在Java的int范围:[-2147483648, 2147483647]
                                              //即 abs(MIN_VALUE) = abs(MAX_VALUE) + 1
        int num = Math.abs(x);
        int res = 0;
        while(num!=0)
        {
            if(res>(Integer.MAX_VALUE-num%10)/10)    //边界溢出检查:若if条件满足,继续向下执行res = res*10+num%10
            rerun 0;                                //就会得到res >= MAX_VALUE,即发生了溢出
            
            res = res*10+num%10;
            num /= 10;                               //此处注意:Java对 / 运算也是截尾的,123/10 = 129/10 =12
        }
        return x>0?res:-res;
    }
}


 

posted @ 2014-12-27 15:41  Mr.do  阅读(94)  评论(0编辑  收藏  举报