1. 程式人生 > >leetcode 虐我篇之(八)Reverse Integer

leetcode 虐我篇之(八)Reverse Integer

    Reverse Integer 這道題的AC率也很高,在打擊到沒信心的時候可以來做做。先來看看題目:

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?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

    其實這道題目講得也很清楚了。就是將一個整數翻轉過來,一開始就想到用整除和取餘來做。如果不考慮整型溢位,那麼這樣子做就已經可以Accepted了。程式碼如下

int reverse(int x) 
{
	int result = 0;	
	
	if (x < 10 && x > (-10))
	{
		return x;
	}
	
	while(x)
	{
		result = result*10 + x%10;
		x /= 10;
	}

	return result;
}

    題目最後面丟擲了一個問題,如果反轉的整數溢位怎麼辦?建議是丟擲異常,或者是傳遞另外一個引數。那就是說加一個引用型別的形參,用來標誌是否溢位。但是關鍵的問題時如何判斷還有在哪裡判斷結果已經溢位了。不知道誰有什麼好方法呢?