9. Palindrome Number
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.
解析
// 9. Palindrome Number
class Solution_9 {
public:
bool isPalindrome(int x) { //+-处理
if (x<0)
{
return false; //负数不当做回文
}
if (x%10==0&&x!=0)
{
return false;
}
if (x<10)
{
return true;
}
int invertnum = 0;
while (x>invertnum) //Revert half of the number
{
invertnum = invertnum * 10 + x % 10;
x /= 10;
}
return x == invertnum||x==invertnum/10; //121 ||1221
}
};
题目来源
C/C++基本语法学习
STL
C++ primer