Reverse Integer

来源:互联网 发布:算法统宗灯的问题 编辑:程序博客网 时间:2024/06/14 12:57

Reverse digits of an integer.

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

click to show spoilers.

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.

数字转换的过程比较简单,重点是对于溢出的边界条件的考虑,在每次乘10之前要先判断下是否乘完,加完之后,会溢出的问题。对于越界的输出,都返回0

代码如下:

public class Solution {    public int reverse(int x) {        if(x==Integer.MAX_VALUE){            return 0;        }        int num = Math.abs(x);        int result = 0;        while(num!=0){            //预先判断14行执行后是否会越界,如果会,就直接返回0,不让其产生越界的可能。            if(result>(Integer.MAX_VALUE-num%10)/10){                return 0;            }                        result = result*10 + num%10;            num/=10;        }                return x>0?result:-result;    }}

参考:http://blog.csdn.net/linhuanmars/article/details/20024837

0 0
原创粉丝点击