9. Palindrome Number(迴文數)
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
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:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
判斷一個整數是否是迴文數。迴文數是指正序(從左向右)和倒序(從右向左)讀都是一樣的整數。
示例 1:
輸入: 121
輸出: true
示例 2:
輸入: -121 輸出: false 解釋: 從左向右讀, 為 -121 。 從右向左讀, 為 121- 。因此它不是一個迴文數。
示例 3:
輸入: 10
輸出: false
解釋: 從右向左讀, 為 01 。因此它不是一個迴文數。
進階:
你能不將整數轉為字串來解決這個問題嗎?
=========================================================
如果用字串就很好解決了,字串s和s.reverse()比較是否相等就出結果了。
=========================================================
第一種方法:網友的思路,翻轉一半能夠避免21億零9這樣的數字溢位問題,很巧妙,但是9000000012這個數字溢位後也和原來的數字不等,int型的溢位在這裡並不會造成影響
class Solution {
public boolean isPalindrome(int x) {
// 負號肯定導致不對稱,或者除了0外能被10整除的也不對稱
// 因為最後一定為0,翻轉後最高位為0,那麼就少了一位
if (x < 0 || (x != 0 && x % 10 == 0)) return false;
int sum = 0;
// 翻轉一半,避免溢位,雖然這裡溢位也不會對結果造成影響
while (x > sum) {
sum = sum * 10 + x % 10;
x /= 10;
}
// 如果是偶數位,翻轉一半直接判斷是否相等
// 如果是奇數位,除去中間位翻轉判斷相等
return x == sum || sum / 10 == x;
}
}
第二種,翻轉全部,幾次測試均比上面的方法快。因為雖然是多做了幾次迴圈和計算,可是第一種方法和非零的數字相比也是需要時間的,比如1234544321會判斷12345和12344,長度相等,暫存器就會一位一位的判斷數字是否相等,當比較的資料量很多組的時候就不一定很優了。
這裡和零比較,一次就能得出誰大,在while的迴圈判斷條件會節省時間。
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x != 0 && x % 10 == 0)) return false;
int sum = 0, temp = x;
while (temp > 0) {
sum = sum * 10 + temp % 10;
temp /= 10;
}
return x == sum;
}
}
Debug code in playground:
class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || (x != 0 && x % 10 == 0)) return false;
int sum = 0, temp = x;
while (temp > 0) {
sum = sum * 10 + temp % 10;
temp /= 10;
}
return x == sum;
}
}
public class MainClass {
public static String booleanToString(boolean input) {
return input ? "True" : "False";
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null) {
int x = Integer.parseInt(line);
boolean ret = new Solution().isPalindrome(x);
String out = booleanToString(ret);
System.out.print(out);
}
}
}
=========================Talk is cheap, show me the code=======================