My first_leetcode_Rever Ingeter 数字翻转java实现(办法集合)

7. Reverse Integer

Reverse digits of an integer. 

Example1: x = 123, return 321 
Example2: x = -123, return -321 
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. 
Note: 
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
一个整数的各个位数翻转. 
 
例1: x = 123, return 321 
例2: x = -123, return -321 
如果整数的最后一位是0,输出应该是什么?比如10,100. 
你注意到翻转的整数可能溢出吗?假设输入是32位整数,那么10000000003的翻转会溢出.该如何处理这个? 
因为这个问题,当翻转之后溢出时,方程应该返回0. 
 
思路:
1.土办法,判断字符输入是否合法,有无+ - 号和多余字符,是否在int 的int_MAX和int_MIN区间范围内,只有在范围内的数字才可以被翻转
2.int型的范围是-2147483648~2147483647,如果你的数字绝对值翻转前不越界,翻转后也有可能越界了,负数的情况也是如此, 比如1000 000 009
3.翻转的时候只需要考虑绝对值翻转后加上符号即可
class Solution {
public int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (Math.abs(res) > Integer.MAX_VALUE / 10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }
        return res;
    }
};

这个办法可以解决一般的情况,但是当数字足够大到达边界值周围的时候需要会报错

我们在这里要做一个改造,增加判断临界值时 的情况

 

参考地址:http://www.jiuzhang.com/solution/reverse-integer/

参考地址:http://www.cnblogs.com/grandyang/p/4125588.html

 

刚开始搞,很多东西玩的不是很透彻,欢迎大家相互讨论哈

 

 
posted @ 2017-08-07 22:38  这个手杀不太0  阅读(412)  评论(4编辑  收藏  举报