码迷,mamicode.com
首页 > 编程语言 > 详细

【LeetCode算法】Reverse Integer

时间:2018-05-18 20:12:39      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:alt   sign   span   tor   .com   not   rev   9.png   val   

LeetCode第7题:

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 store integers within the 32-bit signed integer range: [?231,  231 ? 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解题思路:

假如:x=1234,y=0

1)y乘以10,x把末位4移除掉,加给y(x=123,y=4)

2)y乘以10,x把末位3移除掉,加给y(x=12,y=43)

3)y乘以10,x把末位2移除掉,加给y(x=1,y=432)

4)y乘以10,x把末位1移除掉,加给y(x=0,y=4321)

代码:

int y = 0;
while(x/10!=0){
    y*=10;
    y+=x%10;
    x/=10;
}
y=y*10 +x;

结果报错

技术分享图片

原因是int的范围是-2147483647~2147483648

leetcode给的input是1534236469,倒转之后是9646324351,导致溢出了。所以要加上溢出判断

最后的代码

class Solution {
    public int reverse(int x) {
        
        int negative = 1;  
        if(x <= Integer.MIN_VALUE)  
            return 0;  
        if(x < 0){  
            x = -x;  
            negative = -1;  
        }  
          
        long y = 0;
        while(x/10!=0){
            y*=10;
            y+=x%10;
            x/=10;
        }
        y=y*10 +x;
          
        if(y > Integer.MAX_VALUE)  
            return 0;  
        else  
            return (int)y * negative; 
    }
}

这也是很坑啊,溢出就输出0,鬼知道啊

【LeetCode算法】Reverse Integer

标签:alt   sign   span   tor   .com   not   rev   9.png   val   

原文地址:https://www.cnblogs.com/anni-qianqian/p/9057725.html

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