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.
解法一:
求出x的逆序数y,判断两者是否相等即可。
时间复杂度:O(k),k为x的位数
class Solution {
public:
int reverse(int x) {
long long y = ;
int num = x; while(num)
{
y = y* + num%;
num /= ;
}
return y; //valid
} bool isPalindrome(int x) {
if(x < )
return false;
if(x == reverse(x))
return true;
else
return false;
}
};
解法二:
转为string类型,然后首尾指针逐字符比较。
时间复杂度:O(k),k为x的位数
class Solution {
public:
bool isPalindrome(int x) {
string xstr = to_string(x);
for(int i=, j=xstr.size()-; i < j; i ++, j --)
{
if(xstr[i] != xstr[j])
return false;
}
return true;
}
};