所以我目前正在通过Project Euler我遇到问题17.问题是
如果数字1到5用文字写出:一,二,三,四,五,那么总共有3 + 3 + 5 + 4 + 4 = 19个字母。
如果所有1到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;
}
}
答案 0 :(得分:0)
“四十”是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
可以重复使用数百+ 7来代替“100”这个词。