1. 程式人生 > >[Leetcode] reverse integer 反轉整數

[Leetcode] reverse integer 反轉整數

case inpu over 測試 style bit color leetcode ask

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).

題意:將一個整數反轉。

思路:這題有幾個要註意的地方:一、正負號;二、反轉後的結果是否溢出。第二點很重要,關於這點題目中有詳細的說明。這裏有兩種解法方法:

方法一:改變返回結果的變量類型為long long ,這樣,若是最終計算的結果超過INT_MAX,就返回0;否則,結構符號輸出即可。

代碼如下:

 1 class Solution {
 2 public:
 3     int reverse(int x) 
 4     {
 5         long long  res=0;
 6         int cur=abs(x);
 7 
 8         while(cur>0
) 9 { 10 res=res*10+cur%10; 11 cur/=10; 12 } 13 if(res>INT_MAX) return 0; 14 return x>=0?res:-res; 15 } 16 };

方法二:不用改變返回的變量類型,在while循環中,在計算res之前,若res>INT_MAX/10,就返回0,因為若是大於,則後續的計算中乘以10 了,還是會大於,所以提前返回。代碼如下:

 1 class Solution {
 2 public:
 3     int reverse(int x) 
 4     {
 5         int res=0;
 6         int cur=abs(x);
 7 
 8         while(cur>0)
 9         {
10             if(res>INT_MAX/10) return 0;
11             res=res*10+cur%10;
12             cur/=10;
13         }    
14         
15         return x>=0?res:-res;   
16     }
17 };

在LeetCode上測試時,第二種方法,明顯好些。

[Leetcode] reverse integer 反轉整數