More:【目錄】LeetCode Java實現html
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.java
Example 1:post
Input: 121 Output: true
Example 2:ui
Input: -121 Output: false Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:htm
Input: 10 Output: false Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:blog
Coud you solve it without converting the integer to a string?ip
遇到數字的題目必定要考慮到正負數和0,以及溢出的狀況。get
思路一:最開始想到的思路,翻轉數字,與原來的數字比較,相等便可。對於溢出的狀況,翻轉後的數字和原來數字也不會相等,不會有影響。可是對於非Java語言的話,這種方法可能不行。string
思路二:仍是翻轉數字,可是隻翻轉一半,這翻轉的一半與剩下的一半進行比較,例如:123321,後半部分翻轉爲123,與前半部分123相等即OK。這裏要特別注意的是:奇數狀況以及個位數爲0的狀況。例如:12321,123210it
思路三:獲取最高位和最低位的數字,從兩邊數字向中間比較。
//思路一:翻轉數字(非Java語言可能不行) public boolean isPalindrome1(int x) { if(x<0) return false; int m=x; int n=0; while(m!=0) { n=n*10+m%10; m/=10; } return n==x; } //思路二:翻轉一半 public boolean isPalindrome2(int x) { if(x<0) return false; if(x!=0 && x%10==0) return false; //防止個位數爲0時誤判爲true。例如10 int n=0; while(x>n) { n=n*10+x%10; x/=10; } return n==x || x==n/10; } //思路三:最高位和最低位數字比較 public boolean isPalindrome3(int x) { if(x<0) return false; int div=1; while(x/div>=10) div*=10; while(x!=0) { if((x%10)!=(x/div)) return false; x=(x%div)/10; div/=100; } return true; }
1. 遇到迴文要想到:
A.翻轉後相等;
B.先後對應位置相等;
C.翻轉一半後相等,可是要注意到奇偶數和個位爲0的狀況。
2.和數字有關時,要注意:正負零,越界。
3.掌握好如何獲取數字最高位的方法。
More:【目錄】LeetCode Java實現