編程語言是 Java,代碼托管在我的 GitHub 上,包括測(cè)試用例。歡迎各種批評(píng)指正!
<br />
題目 —— Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
Some hints:
Could negative integers be palindromes? (ie, -1)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer", you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
<br >
解答
-
題目大意
判斷一個(gè)整數(shù)是否是回文數(shù),不使用額外的存儲(chǔ)空間。一些提示:
負(fù)數(shù)可能是回文數(shù)嗎?
如果你考慮把整數(shù)轉(zhuǎn)換為字符串,注意題目中要求不使用額外空間。
你也可以嘗試反轉(zhuǎn)這個(gè)整數(shù)。然而,如果你解決了問題 "Reverse Integer",就會(huì)知道反轉(zhuǎn)整數(shù)可能會(huì)造成溢出。如何解決這個(gè)問題? -
解題思路
- 根據(jù)提示,采用 "Reverse Integer" 思路,但反轉(zhuǎn)整個(gè)數(shù)可能會(huì)引起溢出,所以我們反轉(zhuǎn)一半,利用回文數(shù)左右對(duì)稱的特性。
- 負(fù)數(shù)不可能是回文數(shù),10 的倍數(shù)需要單獨(dú)處理,因?yàn)榉崔D(zhuǎn)時(shí)開頭的數(shù)字為 0。
代碼實(shí)現(xiàn)
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0 || x != 0 && x % 10 == 0) {
return false;
}
int reverse = 0;
while (reverse < x) {
reverse = reverse * 10 + x % 10;
x = x / 10;
}
return (x == reverse) || (x == reverse/10);
}
}
-
小結(jié)
聯(lián)想到利用回文數(shù)對(duì)稱的特性,反轉(zhuǎn)一半的數(shù)字,有一點(diǎn)難度。注意整數(shù)可能是奇數(shù)位或者偶數(shù)位,所以 x 和 reverse 的大小需要再判斷。