我写了下面的代码来查找数字是否是回文。但是当我编译并运行代码时,它会在代码块10.05和12.11,13.12中返回不同的结果。
我尝试了编号为12321的代码。代码块10.05返回“数字12321有5位数,是一个回文数”。代码块12.11和13.12返回“数字12321有5位数而不是回文数”。
这是代码。
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int num, tmp, tmp2, i, k, last_num=0, check_num;
cout<<"Enter a number : ";
cin>>num;
tmp=num;
check_num=num;
for(i=1; tmp>=10; ++i)
{
tmp=(tmp-(tmp%10))/10;
}
cout<<"The number "<<num<<" has "<<i<< " digits ";
for(k=i-1; k>=0; k--)
{
tmp2 = num%10;
last_num+=tmp2*pow(10,k);
num=(num-(num%10))/10;
}
if(check_num == last_num)
{
cout<<"and is a palindrome number"<<endl<<endl;
}
else
{
cout<<"and is NOT a palindrome number"<<endl<<endl;
}
return 0;
}
答案 0 :(得分:2)
您的代码过度,不必要地复杂且不正确(因为我已经提到的浮点数问题,即pow()
返回的值可能不准确)。
你可以用更简单,更简洁的方式实现这一点:以相反的顺序从数字中建立数字,然后检查以这种方式获得的数字是否与原始数字匹配:
int ispal(unsigned long long n)
{
unsigned long o = n;
unsigned long long k = 0;
while (n) {
k *= 10;
k += n % 10;
n /= 10;
}
return o == k;
}
(unsigned long long
仅用于代替普通int
,以使此功能尽可能大的数量。)
答案 1 :(得分:0)
跟进我和H2CO3之间的评论主题,我在这里提供了字符串方法和检查回文的数字方法之间的比较:
#include <iostream>
#include <string>
#include <ctime>
int ispal(unsigned long long n)
{
unsigned long long o = n;
unsigned long long k = 0;
while (n) {
k *= 10;
k += n % 10;
n /= 10;
}
return o == k;
}
int ispalc(char* s)
{
char *e;
e = s + strlen(s) - 1;
while(s < e)
{
if( *s++ != *e-- ) return 0;
}
return 1;
}
int main(void) {
unsigned long long num;
int ii;
time_t startT, endT, diff1, diff2;
char nums[128];
std::cout<<"Enter a number : ";
std::cin>>num;
if (ispal(num) != 0) std::cout << "It is a palindrome" << std::endl;
else std::cout << "It is not a palindrome" << std::endl;
sprintf(nums, "%lld", num);
if (ispalc(nums) != 0) std::cout << "It is a palindrome" << std::endl;
else std::cout << "It is not a palindrome" << std::endl;
startT = clock();
for(ii = 0; ii < 1000000; ii++) ispal(num);
endT = clock();
diff1 = (endT - startT);
startT = clock();
for(ii = 0; ii < 1000000; ii++) ispalc(num);
endT = clock();
diff2 = (endT - startT);
printf("using numbers: %.2lf us\n", diff1 * 1000.0 / CLOCKS_PER_SEC );
printf("using strings: %.2lf us\n", diff2 * 1000.0 / CLOCKS_PER_SEC );
return 0;
}
注意事项:
unsigned long long
的类型;以及函数内部o
的类型(unsigned long
)。这使得代码稍微快一些,因为它没有花时间进行转换。鼓声......有了上述警告,时间表现为:
Enter a number : 123454321
It is a palindrome
It is a palindrome
using numbers: 68.51 us
using strings: 26.27 us
Enter a number : 1234567
It is not a palindrome
It is not a palindrome
using numbers: 53.03 us
using strings: 11.78 us
胜利者对我来说似乎很清楚 - “字符串有它”。