[leetcode]Reverse Integer

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   strong   

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?

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

這道題出的挺好,但是對答案的處理非常不好,tip中顯式的聲明了溢出該怎麼辦,但是case中並未給出處理,說白了,case中壓根就沒有給出可能溢出的case。因此下面的代碼可以過

 1 public class Solution { 2     public int reverse(int x) { 3         boolean isPositive = x > 0?true:false; 4         int tem = Math.abs(x); 5         int result = 0; 6         while(tem!=0){ 7             int temp = tem % 10; 8             tem /= 10; 9             result = 10 * result + temp;10         }11         return isPositive?result:-result;12     }13 }
View Code

 

當然上面的代碼,雖然過了,但是藏有很大的bug,下面這段代碼對上面可能溢出的情況做出了處理,當返回結果溢出時,返回Integer.MAX_VALUE或者Integer.MIN_VALUE

 1 public class Solution { 2   public int reverse(int x) { 3         int result = 0; 4         boolean isNegative = x < 0 ? true : false;  5         int n = Math.abs(x); 6         while(n!=0){ 7             int temp = n % 10; 8             n /= 10; 9             if(!isOverFlow(result, temp, isNegative) ){10                 result = 10 * result + temp;11             }else{12                 result = !isNegative ? Integer.MAX_VALUE:Integer.MIN_VALUE;13             }14         }15         return isNegative ? -result : result;16     }17     private boolean isOverFlow(int num,int tem, boolean isNegative){18         if(!isNegative){19             //Integer.MAX_VALUE = 214748364720             if( (Integer.MAX_VALUE - tem) / 10 < num ) return true;21             return false;22         }else{23             //Integer.MIN_VALUE = -214748364824             if( (Integer.MIN_VALUE + tem) / 10 > -num ) return true;25             return false;26         }27     }28 }

FYI

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.