我已成功确定乘以哪两个数字会产生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);
}
}
}
}
答案 0 :(得分:1)
不是打印出回文,而是将数字放在List&lt; int&gt;中。完成循环后,调用list.Sort()。
答案 1 :(得分: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);
}
}
答案 2 :(得分: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;