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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

 
 这里是提醒注意两点:1,100转过来以后0不要了。2,注意溢出
对于最后0的处理,因为res=res*10+x%10;0相当于没有加了,所以就是处理了
注意:负数%10,负数/10,结果都是负数。。这点对这题很关键
 
//本体关键点是如何判断溢出。
//推荐解答用的是用long类型存储结果,如果结果大于0x7fffffff或者小于0x80000000就溢出
//我的解法是每次计算新的结果时,再用逆运算判断与上一次循环的结果是否相同,不同就溢出
public int reverse(int x) {
        int res=0;
        while(x!=0){
            //最后一位
            int tail=x%10;
            int newRes=res*10+tail;
            //如果newRes-tail)/10!=res说明产生了溢出
            if((newRes-tail)/10!=res)
                return 0;
            res=newRes;
            x=x/10;
        }
        return res;
    }
原文地址:https://www.cnblogs.com/xiaolovewei/p/8034787.html