題目描述如圖:
回文數(shù)
解法基本分為兩類搜骡,一類是轉(zhuǎn)成字符數(shù)組,然后逐個(gè)比較左邊和右邊的字符密似,或者是轉(zhuǎn)成字符串秀撇,然后反轉(zhuǎn)燕酷,再進(jìn)行比較粮揉,其本質(zhì)都是單個(gè)字符的比較膊畴,大家都能想到织中,就不寫了锥涕。
另一類是直接對(duì)數(shù)字進(jìn)行操作,leetcode上有人例舉了狭吼,還不錯(cuò)层坠。我寫完之后,看別人的代碼刁笙,簡(jiǎn)潔好多破花,自嘆不如(不過(guò)我這個(gè)是支持負(fù)數(shù)回文數(shù)的??)直接貼代碼:
private static boolean isPalindrome(int value) {
// 除了 head 剩余有幾位
int count = getCount(value);
// 相當(dāng)于 2332 => number = 2000;
int number = (int) Math.pow(10, count);
for (; value > 9 || value < -9;) {
// 第一位數(shù)
int head = value / number;
// 個(gè)位數(shù)
int tail = value % 10;
if (head != tail) {
return false;
}
// 去掉 head 和 tail 例如 2332 => 33
count -= 2;
value = (value - (number * head + tail)) / 10;
int tmpCount = getCount(value);
// head 之后有一個(gè)或多個(gè) 0 需要處理下
if ((tmpCount = (count - tmpCount)) > 0 && value != 0) {
int pow = (int) Math.pow(10, tmpCount);
// 除了后 再往回乘 看是否相等
int tmp = value / pow;
if (tmp == 0 || value != tmp * pow) {
return false;
}
value = tmp;
}
// 更新
count = getCount(value);
number = (int) Math.pow(10, count);
}
return true;
}
private static int getCount(int value){
int tmp = value;
int count = 0;
while (tmp > 9 || tmp < -9) {
tmp /= 10;
count++;
}
return count;
}
回文數(shù)