目录
原题传送门
题解
先分析一下情况,我们可以看到输入是包括正负数的,以及隐含条件十进制。
所有负数因为带有负号,所以一定false;
非负数中,一位数一定为true;
所以实际上设计的函数需要处理的情况是不小于10的。
那么接下来
常规思路就是转成字符串对比,这样一来长度和获取位置上的字符都迎刃而解
class Solution {
public:
bool isPalindrome(int x) {
bool compareResult{false}; //需要返回的结果,默认为0
if (x < 0)
{
}
else if (x >= 0 && x < 10)
{
compareResult = true;
}
else
{
std::string strX = std::to_string(x);
int strXlen = strX.length();
int count = strXlen / 2;//需要对比的次数
auto indexBegin = 0;
auto indexEnd = strXlen - 1;
while (count--)
{
if (strX[indexBegin] == strX[indexEnd])
{
compareResult = true;
}
else
{
compareResult = false;
break;
}
indexBegin++;
indexEnd--;
}
}
return compareResult;
}
};
进阶题解
我们可以看到原题的下方有一行小字:能不转换成字符串来解决吗?
需要解决的问题有两个:
1.获取长度
循环除10进行计数直到结果为0(这里我们知道常规使用/得到的是商,得到余数需要使用%),这里我们默认为十进制。进制是一个需要注意的问题!
2.获取位置上的字符
在上一个提到的方案中,如果把目光放到余数上。我们会发现如果不存在额外空间使用的约束时,可以使用容器来保存余数,容器的大小就是目的1的答案。
class Solution {
public:
std::vector<int> X{};
bool isPalindrome(int x) {
bool compareResult{false}; //需要返回的结果,默认为0
if (x < 0)
{
}
else if (x >= 0 && x < 10)
{
compareResult = true;
}
else
{
int count = X.size();
auto indexBegin = 0;
auto indexEnd = count - 1;
while (count--)
{
if (X[indexBegin] == X[indexEnd])
{
compareResult = true;
}
else
{
compareResult = false;
break;
}
indexBegin++;
indexEnd--;
}
}
return compareResult;
}
void getIntegerNumLengthWithNone(const int value, const int hexadecimal = 10 /*进制,默认为十进制*/)
//原地计算
{
X.clear();
int num = value;
while (num != 0) {
num /= hexadecimal;
X.push_back(num % hexadecimal);
}
return ;
}
};