两个 3 位数的回文数乘积 - Project Euler Solution 4 - 蛮力不起作用

Palindrome number product of two 3-digit numbers - Project Euler Solution 4 - Brute Force not working

我正在使用这段代码来解决问题。 4 关于欧拉计划。问题如下:

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.

我已经尝试解决问题了。我的代码 returns 是一个回文数,也是一个相当大的数字。但这是不正确的。我还在 MathBlog.dk 找到了正确的解决方案。但是我的代码有什么问题? --

long result = 0;
for (long x = 100; x <= 999; x++)
{
    for (long y = 100; y <= 999; y++)
    {
        long num = x * y;
        if (num.ToString() == StringFunctions.ReverseString(num.ToString()))
        {
                result = num;
        }
    }
}
Console.WriteLine("Result : {0}", result);

StringFunctions.RevereString函数如下:

public static class StringFunctions
{
    public static string ReverseString(string s)
    {
        string result = "";
        for (int i = s.Length - 1; i >= 0; i--)
        {
            result += s.Substring(i, 1);
        }
        return result;
    }
}

我的代码 returns 580085 但正确答案是 906609。我不想知道更好的解决方案。我只想知道为什么 我的 代码不起作用。

任何帮助将不胜感激。提前致谢。

你的结果存储的是从循环中得到的最后一个回文数,而不是最大的一个。

变量XY都从100迭代到999

想象一个情况,当(假设所有获得的数字都是回文)x = 500和y = 500。它会比x = 990和y = 100更早执行。但是在更早的情况下回文更大但是你的代码存储较小的。使用 if 条件获取最大回文:

long result = 0;
for (long x = 100; x <= 999; x++)
{
    for (long y = 100; y <= 999; y++)
    {
        long num = x * y;
        if (num.ToString() == StringFunctions.ReverseString(num.ToString()))
        {
            if(result < num)
            {
            result = num;
            }
        }
    }
}
Console.WriteLine("Result : {0}", result);