題目要求
??Determine whether an integer is a palindrome. Do this without extra space.
??題目翻譯:判斷一個(gè)Integer是否是回文數(shù)字为黎。程序不開辟額外的空間。
題目分析
??最開始的思路是把比較數(shù)字的第一位和最后一位虚缎,并截?cái)嗟谝晃缓妥詈笠晃惶佟1热纾簲?shù)字是12321为迈,比較首尾密浑,然后截?cái)嗟钟玫?32挎挖,依次比較跷究。然而出現(xiàn)了一個(gè)問題:當(dāng)輸入帶有0時(shí)姓迅,比如1000021時(shí),截?cái)鄷l(fā)生遺漏俊马,比如截?cái)?000021首尾丁存,我們期望得到00002,結(jié)果得到的是2柴我,因此出現(xiàn)錯(cuò)誤的結(jié)果解寝。
??調(diào)整的思路是取出首尾位,不截?cái)嗨胰濉<僭O(shè)輸入123321聋伦,比較2的時(shí)候,高位的2是這樣得來的:(123321/10000)%10 界睁;低位的2是這樣得來的:(123321%100)/10
泛化的情況如下:
??len = 數(shù)字位數(shù)-1; // 比如12321觉增,len=4
??first = (x / (int)Math.pow(10, i)) % 10;
??last = (x % (int)Math.pow(10, len+1-i)) / ((int)Math.pow(10, len-i));
實(shí)現(xiàn)代碼
package com.linsiyue;
public class Solution {
public boolean isPalindrome(int x) {
if (x<0) return false;
if (x<10) return true;
long n = 1;
int first = -1, last = -1, len = 0;
while (x >= n){
n = n*10;
len++;
}
len--;
for (int i = len; i > len/2; i--) {
first = (x / (int)Math.pow(10, i)) % 10;
last = (x % (int)Math.pow(10, len+1-i)) / ((int)Math.pow(10, len-i));
if (first != last) return false;
}
return true;
}
}