【leetcode】Palindrome Number (easy)

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.

思路:

不能用额外的空间,数字还有可能过大。 处理方法是把数字截为两半,后半段翻转与前半段对比

class Solution {
public:
bool isPalindrome(int x) {
int y = ; //把x的后半段反过来
if(x > && x % == ) //如果大于0的数字以0结尾 一定不是回文
return false;
if(x >= && x < ) //个位数一定是回文
return true;
while(y <= x)
{
if(y == x || (x / > && y == x / )) //偶数个数字 和奇术个数字都要考虑
return true;
y = y * + x % ;
x = x / ; //把x后面给y了的截掉
}
return false;
}
};

同样思路,更简洁的代码:

class Solution {
public:
bool isPalindrome(int x) {
int i = ;;
if ((x % == && x != ) || x < ) return false;
while (i < x) {
i = i * + x % ;
x = x / ;
}
return (i == x || i / == x);
}
};
上一篇:九度 题目1437:To Fill or Not to Fill


下一篇:CTreeCtrl 控件使用总结