首页 > 其他 > 详细

Reverse Integer

时间:2015-07-01 18:21:15      阅读:163      评论:0      收藏:0      [点我收藏+]

原题链接https://leetcode.com/problems/reverse-integer/

题目:

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.

Update (2014-11-10):
Test cases had been added to test the overflow behavior.

原本是有buge(不考虑溢出)也能通过的,但是现在不行了,需要考虑溢出问题

下面是我用Java写的,AC通过。。(其中判断溢出的部分参考了他人代码,链接在此:http://blog.csdn.net/stephen_wong/article/details/28779481

public class Solution {
    public int reverse(int x) {
        int res = 0;
        int flag = 0;
        
        if(checkOverflow(x)) {
            return 0;
        } else {
        
            if(x < 0) {
                flag = 1;
                x = -x;
            }
            
            while(x>0) {
                res = x % 10 + res * 10;
                x /= 10;
            }
            
            if(flag == 1) {
                return -res;
            }
            return res;
        }
    }
    
    public static boolean checkOverflow(int x) {
		if(x/1000000000 == 0) {  //x的绝对值小于1000000000,不越界
			return false;
		} else if(x == Integer.MIN_VALUE) {//Integer.MIN_VALUE = -2147483648,反转后越界,也没法按下述方法取绝对值(下面绝对值的方法相当于对排除了正、负数的影响)
			return true;
		}
		
		x = Math.abs(x);
		 // x = d463847412 ->  2147483647. (参数x,本身没有越界,所以d肯定是1或2)   
		 // or -d463847412 -> -2147483648. 
		for(int cmp = 463847412; cmp != 0; cmp/=10,x/=10) {
			if(x%10 > cmp%10) {
				return true;
			} else if(x%10<cmp%10) { //x从个位(低位)到高位依次与整型上界从高位到地位比较,x的每一位必须小于整型上界的每一位才不会越界,否则越界
				return false;
			}
		}
		return false;
	}
    
}


 

版权声明:本文为博主原创文章,未经博主允许不得转载。

Reverse Integer

原文:http://blog.csdn.net/yangyao_iphone/article/details/46711775

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!