数字回文函数不返回最大回文

问题描述 投票:0回答:1

我正在尝试创建一个函数来查找由 3 位数因子组成的最大回文数。当我运行代码时,它找到一个回文,但它不是最大的。不要批评我的代码,尤其是 goto,因为我对 C:

还很陌生
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int isPalindrome(int number) {
    int palindrome = 1;
    char *str = (char *)malloc(8 * sizeof(char));
    sprintf(str, "%d", number);
    int len = strlen(str);
    for (int i = 0; i < len; i++) {
        if ((str[i] == str[len - (i+1)]) && palindrome) continue;
        else palindrome = 0;
    }
    free(str);
    return palindrome;
}

int main(void) {
    char* omg = "\xF0\x9F\x98\xB2";
    int factorI = 0;
    int factorJ = 0;
    for (int i = 999; i >= 100; i--) {
        for (int j = 999; j >= 100; j--) {
            if (isPalindrome(i * j)) {
                factorI = i;
                factorJ = j;
                goto end_loop;
            }
        }
    }
    end_loop: printf("Done! Found palindrome. (%s%s%s)\n", omg, omg, omg);
    printf("i: %d\nj: %d\n", factorI, factorJ);
    printf("PALINDROME: %d", factorI * factorJ);
    printf("\n\nHello World\n");
    return 0;
}

当我运行代码时,我得到这个:

Done! Found palindrome. (😲😲😲)
i: 995
j: 583
PALINDROME: 580085

Hello World

但这似乎不是最大的回文,因为当我将其输入到Project Euler时,它会将解决方案标记为不正确。谁能帮助调试我的代码并看看我哪里搞砸了?我又看了三遍,却什么也没发现。 请不要告诉我正确的因子/回文,只需帮助我编写代码即可。

c factors
1个回答
0
投票

你的算法有问题。对于 999 到 100 之间的每个数字,它会从 999 循环到 100 并检查第一个回文数字。但这还不是最大的数字。

即906609,由913和993组成。

您可以使用循环,但您需要继续循环并与最大值进行比较。我们首先将其设置为

0

int main(void) {
    int factorI = 0;
    int factorJ = 0;
    int max = 0;
    for (int i = 999; i >= 100; i--) {
        for (int j = 999; j >= 100; j--) {
            int ij = i * j;
            if (isPalindrome(ij) && ij > max) {
                factorI = i;
                factorJ = j;
                max = ij;
            }
        }
    }
    printf("Done! Found palindrome.\n");
    printf("i: %d\nj: %d\n", factorI, factorJ);
    printf("PALINDROME: %d\n", max);

    return 0;
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.