Reverse Integer leetcode java

愛做飯的小瑩子發表於2014-08-02

題目

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

 

題解

 解題思想是: 用一個queue來存當前輸入數字從個位開始到最高位的數字。依次取得這些數字的方法是,當前數字對10取餘數,然後當前數字減去這個餘數再除以10,依次迴圈處理。並且在這個迴圈過程中記錄位數。在下一步還原時,依據當前位數算出要乘以多少個0,從queue中取出來的數就是從個位開始的數,相當於reverse了。

 

因為取得數字的過程中依據取餘,所以符號可以得以保留,並且對於10,100也能保證reverse的正確性。 對於溢位並沒有做特殊處理。

程式碼如下:

 1     public int reverse(int x) {
 2         Queue<Integer> q = new LinkedList<Integer>();
 3         int count = 0;
 4         while(x!=0){
 5          count++;
 6          int r=x%10;
 7          q.add(r);
 8          x=(x-r)/10;
 9          }
10         
11         int nx = 0;
12         for(int i=count;i>0;i--){
13             int temp = q.poll();
14             int j=i;
15             int carry=1;
16             while(j>1){
17             carry=carry*10;
18             j--;
19             }
20             nx = nx+temp*carry;
21         }
22         return nx;
23      }

 然後在網上搜尋到Code ganker(http://blog.csdn.net/linhuanmars/article/details/20024837)的解法,

感覺就更加精煉,而且對邊界條件(越界問題)考慮的非常巧妙,值得學習。

像他再博文中提到:“這種題的考察重點並不在於問題本身,越是簡單的題目越要注意細節,一般來說整數的處理問題要注意的有兩點,一點是符號,另一點是整數越界問題

注意Integer.MIN_VALUE的絕對值是比Integer.MAX_VALUE大1的,所以經常要單獨處理。

程式碼如下:

 1 public int reverse(int x) {
 2     if(x==Integer.MIN_VALUE)
 3         return Integer.MIN_VALUE;
 4     int num = Math.abs(x);
 5     int res = 0;
 6     while(num!=0){
 7         if(res>(Integer.MAX_VALUE-num%10)/10)//非常巧妙的判斷了越界問題
 8             return x>0?Integer.MAX_VALUE:Integer.MIN_VALUE;
 9         res = res*10+num%10;
10         num /= 10;
11     }
12     return x>0?res:-res;
13 }

 

 

 

相關文章