Project Euler Task 17
本文关键字:Task Euler Project | 更新日期: 2023-09-27 18:22:43
所以我目前正在处理Project Euler,我遇到了问题17。问题是
如果数字1到5是用单词写出来的:一、二、三、四、五,那么总共使用了3+3+5+4+4=19个字母。
如果从1到1000(包括1000)的所有数字都用单词写出来,会使用多少个字母?
就我个人而言,我认为问题会很直接。现在,我知道我的代码不是最优化的,我也知道我可以在网上找到解决方案。但我只是在寻找我的代码出了什么问题。我得到的答案是21224,而正确答案是21124。
int Sum = 0;
int Hundred;
int Ten;
int One;
void Count()
{
for(int i = 0; i < 10; i++)
{
Hundred = i;
for(int j = 0; j < 10; j++)
{
Ten = j;
for(int k = 0; k < 10; k++)
{
One = k;
switch(i)
{
case 0:
Tens();
break;
case 1:
Sum += 3;
Sum += 7;
Tens();
break;
case 2:
Sum += 3;
Sum += 7;
Tens();
break;
case 3:
Sum += 5;
Sum += 7;
Tens();
break;
case 4:
Sum += 4;
Sum += 7;
Tens();
break;
case 5:
Sum += 4;
Sum += 7;
Tens();
break;
case 6:
Sum += 3;
Sum += 7;
Tens();
break;
case 7:
Sum += 5;
Sum += 7;
Tens();
break;
case 8:
Sum += 5;
Sum += 7;
Tens();
break;
case 9:
Sum += 4;
Sum += 7;
Tens();
break;
}
}
}
}
Sum += 11 + 99*9*3; //Taking into account the "one thousand" and the "and"s
label1.Text = Sum.ToString();
}
void Tens()
{
switch (Ten)
{
case 0:
Ones();
break;
case 1:
switch (One)
{
case 0:
Sum += 3;
break;
case 1:
Sum += 6;
break;
case 2:
Sum += 6;
break;
case 3:
Sum += 8;
break;
case 4:
Sum += 8;
break;
case 5:
Sum += 7;
break;
case 6:
Sum += 7;
break;
case 7:
Sum += 9;
break;
case 8:
Sum += 8;
break;
case 9:
Sum += 8;
break;
}
break;
case 2:
Sum += 6;
Ones();
break;
case 3:
Sum += 6;
Ones();
break;
case 4:
Sum += 6;
Ones();
break;
case 5:
Sum += 5;
Ones();
break;
case 6:
Sum += 5;
Ones();
break;
case 7:
Sum += 7;
Ones();
break;
case 8:
Sum += 6;
Ones();
break;
case 9:
Sum += 6;
Ones();
break;
}
}
void Ones()
{
switch(One)
{
case 0:
break;
case 1:
Sum += 3;
break;
case 2:
Sum += 3;
break;
case 3:
Sum += 5;
break;
case 4:
Sum += 4;
break;
case 5:
Sum += 4;
break;
case 6:
Sum += 3;
break;
case 7:
Sum += 5;
break;
case 8:
Sum += 5;
break;
case 9:
Sum += 4;
break;
}
}
"四十"是5个字母,但在Tens
方法中有
case 4:
Sum += 6;
Ones();
break;
"四十"会出现100次,所以有区别。
就我个人而言,我认为最好使用将数字映射到字母数的数组,而不是使用一堆开关盒。我就是这样做的,我只是将我的值与你的值进行了双重检查,以找出错误。类似的东西
var onesDigit = new[] { 0, 3, 3, 5, 4, 4, 3, 5, 5, 4 };
var teens = new[] { 3, 6, 6, 8, 8, 7, 7, 9, 8, 8 };
var tensDigit = new[] { 0, 0, 6, 6, 5, 5, 5, 7, 6, 6 };
并且onesDigit
可以与"百"字的"百"+"七"重复使用。