原题链接:Palindrome Number
乍一看,这题挺简单,直接将 int 转化为 string 处理,几行代码完事
class Solution
{
public:
bool isPalindrome(int x)
{
string s = to_string(x);
string s1 = s;
std::reverse(s.begin(), s.end());
if (s == s1)
return true;
else
return false;
}
};
但是题目下方有个 follow up:Coud you solve it without converting the integer to a string?
enmmmm…陷入沉思
可通过循环,先计算数字的首位和末尾,然后去除首尾和末尾,依次循环可得结果
class Solution
{
public:
bool isPalindrome(int x)
{
if (x < 0)
return false;
else if (0 == x)
return true;
else
{
auto len = static_cast<int>(log10(x)) + 1; // 计算数字位数
if (1 == len)
return true;
for (int i = len-1, j = 1; j <= (len+1)/2; j++) // j 控制循环次数
{
int front = x / static_cast<int>(pow(10, i)); //首位
int back = x % 10; // 末尾
if (front != back)
return false;
// x 掐头去尾(去除首位和末尾),进行下一轮计算
x = (x - front * static_cast<int>(pow(10, i))) / 10;
i = i - 2;
}
return true;
}
}
};


本文探讨了在不将整数转换为字符串的情况下,如何判断一个整数是否为回文数。通过计算数字的位数,比较首位和末位,逐步去除首尾进行循环验证,提供了一种高效解决方案。

385

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



