More:【目錄】LeetCode Java實現html
https://leetcode.com/problems/reverse-integer/java
Given a 32-bit signed integer, reverse digits of an integer.git
Example 1:post
Input: 123 Output: 321
Example 2:ui
Input: -123 Output: -321
Example 3:this
Input: 120 Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.code
這道題要注意幾個狀況:1.題目要求只能用int類型;2. 要考慮到負數的狀況;3.考慮先後爲0的狀況,例如00100翻轉後爲1,而不是100;4. 考慮到翻轉後的數字越界的狀況,即要注意answer>Integer.MAX_VALUE或者answer<Integer.MIN_VALUE的狀況。htm
解法一:(乘以10以前,絕對值與Integer.MAX_VALUE/10比較)blog
public int reverse(int x) { int ans=0; while(x!=0){ if(Math.abs(ans)>Integer.MAX_VALUE/10) // if(res>Integer.MAX_VALUE/10 || res<Integer.MIN_VALUE/10) return 0; ans=ans*10+x%10; x/=10; } return ans; }
解法二:(越界的狀況下,ans/10的結果將會 和以前不一致)ip
public int reverse(int x) { int ans=0; while(x!=0){ int temp=ans*10+x%10; if(temp/10!=ans) return 0; ans=temp; x/=10; } return ans; }
1. 利用ans=ans*10+x%10進行翻轉。
2. 本題思考時必需要注意到正負數的狀況。利用ans=ans*10+x%10進行翻轉時,則不用區分正負,由於負數%10的結果也仍是負數。
3. 必定要注意溢出的狀況,解法一在乘以10以前,用絕對值與Integer.MAX_VALUE/10比較;而解法二是根據溢出後的結果/10與以前不一致來判斷。兩種方法都要好好記住。
4. 解法一中,爲何不用判斷Math.abs(ans)==Integer.MAX_VALUE/10的狀況?
緣由是,方法接收的參數x也爲int類型,其最高位只能是1或者2,因此Integer.MAX_VALUE/10+1或者2都不會超出Integer.MAX_VALUE的範圍。
5. Integer.MAX_VALUE=0x7FFF FFFF=2^31-1=2147483647;Integer.MIN_VALUE=0x8000 0000=-2^31=-2147483648.
6. 上面的邊界值,最高位爲2,最低位爲7和8。一共10位數字。
More:【目錄】LeetCode Java實現