Leet Code OJ 7. Reverse Integer [Difficulty: Easy]
題目:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
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.
翻譯:
反轉(zhuǎn)一個整形數(shù)的數(shù)值。
你是否考慮了這些?
在寫代碼之前,這里有一些好問題需要被提出來討論一下。如果你已經(jīng)考慮到了這些問題,在面試中會是一個加分項。
如果整數(shù)的某位是0,那輸出結(jié)果應該是怎樣的?例如,像10,100這種用例。
你注意到反轉(zhuǎn)后的整數(shù)可能導致溢出嗎?假定輸入是一個32位的整數(shù),然后1000000003的反轉(zhuǎn)后的結(jié)果會導致溢出。你怎樣處理這些溢出?
考慮到這個問題,我們假定你的程序在反轉(zhuǎn)溢出時返回0。
分析:
這道題目看似簡單,實則非常容易出錯,通過率也較低。原因在于結(jié)果溢出的處理上(根據(jù)題目的補充說明,溢出返回0),做題時,需要考慮以下幾種特殊情況:
1. 在做反轉(zhuǎn)的時候,我把輸入的數(shù)字統(tǒng)一轉(zhuǎn)化為正數(shù)處理。這個時候可能產(chǎn)生第一次溢出。
2. 當輸入為類似100時,檢查輸出是否正確。
3. 在反轉(zhuǎn)的過程中,由于可能產(chǎn)生溢出,我將中間結(jié)果采用long保存。
4. 將long轉(zhuǎn)化為int時,需要根據(jù)輸入的符號,再次判斷是否溢出。
代碼:
public class Solution {public int reverse(int x) {boolean flag=false;if(x<0){flag=true;if(-(long)x>Integer.MAX_VALUE){return 0;}x=-x;}long result=0;while(true){result=result*10+x%10;if(x<10){break;}x/=10;}if(flag){if(-result<Integer.MIN_VALUE){return 0;}return -(int)result;}if(result>Integer.MAX_VALUE){return 0;}return (int)result;} }總結(jié)
以上是生活随笔為你收集整理的Leet Code OJ 7. Reverse Integer [Difficulty: Easy]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Leet Code OJ 38. Cou
- 下一篇: Leet Code OJ 206. Re