检查数字是否是回文 [英] Checking if a number is a palindrome
本文介绍了检查数字是否是回文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试使用以下代码检查数字是否为回文式:
I've tried to check whether a number is a palindrome with the following code:
unsigned short digitsof (unsigned int x)
{
unsigned short n = 0;
while (x)
{
x /= 10;
n++;
}
return n;
}
bool ispalindrome (unsigned int x)
{
unsigned short digits = digitsof (x);
for (unsigned short i = 1; i <= digits / 2; i++)
{
if (x % (unsigned int)pow (10, i) != x % (unsigned int)pow (10, digits - 1 + i))
{
return false;
}
}
return true;
}
但是,以下代码无法检查回文-即使数字是回文,也总是返回false.
However, the following code isn't able to check for palindromes - false is always returned even if the number is a palindrome.
任何人都可以指出错误吗?
Can anyone point out the error?
(请注意:我不希望将其变成字符串并反转它以查看问题出在哪里:相反,我有兴趣知道上面代码中的错误在哪里.)
(Please note: I'm not interested to make it into a string and reverse it to see where the problem is: rather, I'm interested to know where the error is in the above code.)
推荐答案
问题是这样的:
x % (unsigned int)pow (10, i)
尝试:
x =504405
i =3
SO I want 4.
x % 10^3 => 504405 %1000 => 405 NOT 4
怎么样
x / (unsigned int)pow (10, i -1) % 10
这篇关于检查数字是否是回文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文