LeetCode(9. Palindrome Number)
Determine whether an integer is a palindrome. Do this without extra space.
click to show spoilers.
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.
知識(shí)點(diǎn):
- 負(fù)數(shù)不會(huì)是回文。
- 由于本題要求"Do this without extra space",在我理解為空間復(fù)雜度應(yīng)該控制在O(1)。所以本題不能用string類型轉(zhuǎn)換來(lái)做。
解題思路:
本題是判斷一個(gè)integer是否為回文。我的做法是,從integer的兩邊開(kāi)始往中間走來(lái)判斷,設(shè)置一個(gè)left變量和一個(gè)right變量。當(dāng)最后剩余的數(shù)據(jù)位數(shù)小于等于二的時(shí)候,進(jìn)行一下簡(jiǎn)單的判斷就可以了。
C++代碼如下:
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false; //negative number is not a palindrome
if (x >= 0 && x <= 9) return true;
//to get the length of digits
int len = 0, x1 = x;
while (x1 > 0){
len++;
x1 /= 10;
}
//from head and from tail to check
int left, right;
while (len > 2){
left = x / pow(10,len-1);
right = x % 10;
if (left != right)
return false;
x = (x - left*pow(10,len-1)) / 10;
len -= 2;
}
if (len == 1)
return true;
else{ // len == 2
if (x/10 == x%10)
return true;
else
return false;
}
}
};