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