Palindrome Number ---- LeetCode 009

时间:2024-06-08 08:03:43

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.

Solution 1: (with extra space)

 class Solution
{
public:
bool isPalindrome(int x)
{
if(x == ) return true;
if(x < ) return false; vector<int> v;
bool flag = true; // 若x = 13314, 则v为4 1 3 3 1
while(x != )
{
v.push_back(x % );
x = x / ;
} auto left = v.begin(), right = prev(v.end());
for(; left < right; ++left, --right) // 注意: left < right
{
if(*left != *right)
{
flag = false;
break;
}
}
return flag;
}
};

Solution 2:

class Solution
{
public:
bool isPalindrome(int x)
{
if(x < ) return false;
else if(x == ) return true; bool flag = true; int temp = x, y = ;
while(x != )
{
y = y * + x % ;
x = x / ;
}
if(y != temp) flag = false;
return flag;
}
};