1. 程式人生 > >Reverse Integer

Reverse Integer

sed handle Coding solution 上界 clas cli while question

原題鏈接: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