您的位置:首页 > 其它

Palindrome Number

2015-08-16 16:14 344 查看
Determine whether an integer is a palindrome. Do this without extra space.

思路:

逆转该数字,看逆转前后是否相等。

确定该数的数量级,一次由两边想中间比较对称的两个数是否相等。

需要注意的是负数是palindrome。

class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
else if(x >=0 && x < 10)
return true;
else{
long ret = 0, tmp = x;
while(tmp){
ret = ret * 10 + tmp % 10;
tmp = tmp / 10;
}
return int(ret) == x;
}
}
};


class Solution {
public:
bool isPalindrome(int x) {
if(x < 0)
return false;
else if(x >=0 && x < 10)
return true;
else{
int len = 1;//数量级
while(x/len >= 10)
len *= 10;
while(x){
int r = x % 10;
int l = x / len;
if(r != l)
return false;
else{
x = (x % len) / 10;
len /= 100;
}
}
return true;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: