题目:
Determine whether an integer is a palindrome. Do this without extra space.
分析:
该题目来源于leetcode。回文串是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。当然整数形式的回文串也是类似的。但负数不是回文串。两种思路:
- 按定义来,依次比较串的首尾,直到中间相隔1个或0个元素(取决于整数是奇数位数还是偶数位数)。优点是当不是回文串时,可以很快发现。如果是回文串,则必须比较全部位数。
- 根据回文串的特点,正反序,其数是相同的。优点是不必按位数来判断。
代码:
<span style="font-size:12px;font-weight: normal;">class Solution {
public:
bool isPalindrome(int x) {
vector<int> v;
int i, j;
if (x == 0)
return true;
while (x)
{
v.push_back(x % 10);
x /= 10;
}
i = 0;
j = v.size()-1;
while (i < j)
{
if (v.at(i++) != v.at(j--))
return false;
}
return true;
}
};</span>
<span style="font-size:12px;font-weight: normal;">class Solution {
public:
bool isPalindrome(int x) {
vector<int> v;
int i, j;
if (x == 0)
return true;
while (x)
{
v.push_back(x % 10);
x /= 10;
}
i = 0;
j = v.size()-1;
while (i < j)
{
if (v.at(i++) != v.at(j--))
return false;
}
return true;
}
};</span>
class Solution {
public:
bool isPalindrome(int x) {
int y = 0;
int t = x;
if (t < 0) //负数不是回文串
return false;
while (t)
{
y = y * 10 + t % 10;
t /= 10;
}
if (y ^ x) //判断正反序是否相等
return false;
return true;
}
};