c - 两个 3 位数字的乘积是回文数

标签 c palindrome

我编写了以下代码,用于查找通过两个 3 位数字的乘积获得的第一个回文数:

#include <stdio.h>

int main()
{
    int pro,d,sum=0,c;
    for (int a=100;a<1000;a++)
    {
        for (int b=a;b<1000;b++)
        {
            pro=a*b;
            d=pro;
            while (d!=0)
            {
                c=d%10;
                sum= sum*10 + c;
                d=d/10;
            }

            if (sum==pro)
            {
                printf("%d is a palindrome \n",sum);
                return 0;
            }
        }
   }
   return 0;
}

但是当我运行代码时它没有给我任何输出。 有什么帮助吗?

最佳答案

您需要在每次迭代或内部 for 循环后重置总和值,否则它将在下一个后续迭代中使用前一个迭代值。

代码:

#include <stdio.h>

int main()
{
   int pro,d,sum=0,c;
 for (int a=100;a<1000;a++)
{
    for (int b=a;b<1000;b++)
    {
        pro=a*b;
        d=pro;
        while (d!=0)
        {
            c=d%10;
            sum= sum*10 + c;
            d=d/10;
        }
        if (sum==pro)
        {
            printf("%d is a palindrome \n",sum);
            return 0;
        }
        sum=0;
    }
}

    return 0;
}

输出:

10201 is a palindrome

关于c - 两个 3 位数字的乘积是回文数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52462386/

相关文章:

c - 多个 fork() 并发

C程序检查字符串是否为回文

c++ - 根据用户输入创建一个字符数组

c++ - 带链表的回文函数

C:检查字符串是否是回文

c - '%' 和格式说明符之间的数字在 scanf 中意味着什么?

c - vim 的高效非交互使用

c - 使用Netbeans测量执行C程序的时间

c++ - O(N ^ 2)时间内的回文分割问题

c - Linux中限制进程读取 "/etc/resolv.conf"文件