Description:
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.
Subscribe to see which companies asked this question.
- 负数不是回文数,返回false
- 如果将数转换成字符串来处理,注意该字符串前边可能包含空格
- 分别讨论字符串长度为奇数和偶数的情况
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
string str = to_string(x);
int i = 0;
while(isspace(str[i]))
i ++;
str.substr(i);
int len = str.length();
bool odd = (len & 0x00000001) ? true : false;
if(odd) {
for(int i = len/2-1, j = len/2+1; i >= 0 && j < len; i -- , j ++)
if(str[i] != str[j])
return false;
}
else {
for(int i = len/2-1, j = len/2; i >= 0 && j < len; i --, j ++)
if(str[i] != str[j])
return false;
}
return true;
}
};