码迷,mamicode.com
首页 > 其他好文 > 详细

Reverse Integer

时间:2017-11-18 23:37:03      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:turn   输入   row   去掉   lin   cep   符号   rpo   res   

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output:  321

 

Example 2:

Input: -123
Output: -321

 

Example 3:

Input: 120
Output: 21

 

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

首先需要明白的是int的范围 32位 -2147483648-->2147483647。

想法是把符号去掉,拿绝对值来处理。这可以利用math.abs()来实现。

其次是在输入是要对输入的数进行判定。

最重要的是在输出的时候也需要对输出值判定。

所以在最好用long类型来接反向的数,因为用int的时候,一旦溢出就会自己处理导致结果不对。

具体是15678204569这个数,倒数第二位是9亿多,再倒数第一位就是90亿,肯定溢出,所以最后要有判断,

不然就会出现错误结果。

class Solution {
    public int reverse(int x) {
     if(x<=Integer.MIN_VALUE||x>=Integer.MAX_VALUE){
           // throw new IllegalArgumentException("Num is Wrong!");
             return 0;
        }
        long res=0 ;
        int flags = x < 0 ? -1 : 1;
        x = Math.abs(x);
        while(x > 0){
               res = res*10+x%10;
               x/=10;

        }
        if(res<=Integer.MIN_VALUE||res>=Integer.MAX_VALUE){
            //throw new IllegalArgumentException("Num is Wrong!");
            return 0;
        }
        int r = (int)res*flags;
        return r;
}
}

  

Reverse Integer

标签:turn   输入   row   去掉   lin   cep   符号   rpo   res   

原文地址:http://www.cnblogs.com/liuchuan9504/p/7858096.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!