0

我已经成功地确定了哪两个数字相乘时会在 C# 中产生数字回文,但是我需要将产品从最低到最高排序。有没有办法做到这一点?

static void LargestPalindrome()
{
    ulong product = 0;
    ulong compare = 0;
    for (uint i = 100; i < 1000; i++) 
    {
        for (uint j = 100; j < 1000; j++)
        {
            product = i * j;
            StringBuilder value = new StringBuilder(product.ToString());

            //Pass string to reverse
            string value_r = Reverse(value.ToString());

            //Check if Numeric Palindrome
            if(value_r.Equals(value.ToString()) && product>compare)
            {      
                Console.WriteLine("{0} x {1} = {2} in reverse {3}", i, j, value, value_r);
            }
        }
    }
}
4

3 回答 3

1

不要打印回文,而是将数字放在 List<int> 中。完成循环后,调用 list.Sort()。

于 2013-01-30T03:51:42.703 回答
0

以下应该足够了。我只是对回文列表进行了排序并将它们打印到控制台屏幕。

static void LargestPalindrome()
{
    ulong product = 0;
    ulong compare = 0;
    List<ulong> results = new List<ulong>();
    for (uint i = 100; i < 1000; i++) 
    {
        for (uint j = 100; j < 1000; j++)
        {
            product = i * j;
            StringBuilder value = new StringBuilder(product.ToString());

            //Pass string to reverse
            string value_r = Reverse(value.ToString());

            //Check if Numeric Palindrome
            if(value_r.Equals(value.ToString()) && product>compare)
            {      
                results.Add(product);
            }
        }
    }

    results.Sort();
    foreach (var palindrome in results)
    {
        Console.WriteLine(palindrome);
    }    
}
于 2013-01-30T03:55:38.123 回答
0

您还可以使用 LINQ:

var palindromes = from i in Enumerable.Range(100, 9900)
                  from j in Enumerable.Range(100, 9900)
                  let product = (i * j)
                  where product.ToString() == new string(product.ToString().Reverse().ToArray())
                  orderby product
                  select product;
于 2013-12-24T23:49:37.380 回答