您的位置:首页 > 其它

【Leet Code】Palindrome Number

2014-08-27 00:55 183 查看


Palindrome Number

Total Accepted: 19369 Total
Submissions: 66673My Submissions

Determine whether an integer is a palindrome. Do this without extra space.

判断一个数整数是不是回文?例如121,1221就是回文,好吧,直接利用前面写过的【Leet
Code】Reverse Integer——“%”你真的懂吗?

不过这里要考虑翻转后,数值溢出的问题,代码如下:

/*
//first method
class Solution {
public:
bool isPalindrome(int x)
{
long long temp = x;
long long  ret = 0;
bool isNegative = false;
if (temp < 0)
{
return false;
}
while (temp)
{
ret = ret * 10 + temp % 10;
temp /= 10;
}
if(x == ret)
{
return true;
}
else
{
return false;
}

}
};
*/


当然,我们还有更好的方法,其实,初见这个题目,第一个想法是取头取尾进行比较,然后把头尾去掉,再循环,直到数值为个位数为止:

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