編程語言是 Java,代碼托管在我的 GitHub 上,包括測試用例。歡迎各種批評指正!
<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 >
解答
-
題目大意
判斷一個整數是否是回文數,不使用額外的存儲空間。一些提示:
負數可能是回文數嗎?
如果你考慮把整數轉換為字符串,注意題目中要求不使用額外空間。
你也可以嘗試反轉這個整數。然而,如果你解決了問題 "Reverse Integer",就會知道反轉整數可能會造成溢出。如何解決這個問題? -
解題思路
- 根據提示,采用 "Reverse Integer" 思路,但反轉整個數可能會引起溢出,所以我們反轉一半,利用回文數左右對稱的特性。
- 負數不可能是回文數,10 的倍數需要單獨處理,因為反轉時開頭的數字為 0。
代碼實現
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);
}
}
-
小結
聯想到利用回文數對稱的特性,反轉一半的數字,有一點難度。注意整數可能是奇數位或者偶數位,所以 x 和 reverse 的大小需要再判斷。