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

Reverse Integer

时间:2017-07-16 13:38:48      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:ast   return   没有   log   git   over   inpu   tps   name   

原题链接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

标签:ast   return   没有   log   git   over   inpu   tps   name   

原文地址:http://www.cnblogs.com/yxysuanfa/p/7190248.html

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