9. Palindrome Number
Determine whether an integer is a palindrome. Do this without extra space.
way-1: force, 强行每次把首位两个数字提出来比较。
way-2:int to string
class Solution {
public:
string itos(int i) // 将int 转换成string,这个函数可以将任何类型转换为string
{
stringstream s;
s << i;
return s.str();
}
bool isPalindrome(int x)
{
//way-1
int xx = x;
if (x < 0)
return false;
int k = 1;
while(xx / 10 != 0)
{
xx = xx / 10;
k++;
}
int x1,x2;
for(int i=0;i<k/2;i++)
{
xx = x;
for(int j=0;j<i;j++)
xx = xx / 10;
x1 = xx % 10;
xx = x;
for(int j=0;j<k-i-1;j++)
xx = xx/10;
x2 = xx % 10;
if(x1 != x2)
return false;
}
return true;
//way-2
/*
string s1 = itos(x);
string s2 = s1;
reverse(s2.begin(), s2.end());
return s1 == s2;
*/
}
};
本文介绍了一种不使用额外空间判断整数是否为回文数的方法。提供了两种实现方式:一种是通过直接比较整数的首尾数字,另一种是将整数转为字符串后进行比较。附带给出了C++代码示例。
250

被折叠的 条评论
为什么被折叠?



