gpt4 book ai didi

c++ - 欧拉计划(#17)

转载 作者:太空狗 更新时间:2023-10-29 21:49:40 26 4
gpt4 key购买 nike

关于欧拉项目的第 17 题指出:

如果数字 1 到 5 用单词写出:一、二、三、四、五,则总共使用了 3 + 3 + 5 + 4 + 4 = 19 个字母。如果把1到1000(一千)的数字全部用文字写出来,要用多少个字母?注意:不要计算空格或连字符。例如,342(三百四十二)包含 23 个字母,115(一百一十五)包含 20 个字母。在写数字时使用“and”符合英国的用法。

我已经检查了我的代码很多次,但找不到为什么它没有正确解决它,任何帮助将不胜感激,谢谢

`#include <iostream>
#include <sstream>

unsigned int value = 11;//one thousand = 11

short small(short x);
void two(short third);

int main()
{
for(short count = 0;count<10;count++)
{
two(count);
}
std::cout<<value;
std::cin.get();
return 0;
}

void two(short third)
{

std::string temp;
if(third>0)
{
third = (small(third) + 10);//10 = and(3) + hundred(7)
}
for(short i = 0;i<20;i++)//0-20
{
value += (small(i) + third);
}
for(short i = 20;i<60;i++)//20-40 + 80-100
{
std::stringstream ss;
ss<<i;
temp = ss.str();
value += ((small(temp[1]-'0') + 6) + third);
}
for(short i = 40;i<70;i++)//40-70
{
std::stringstream ss;
ss<<i;
temp = ss.str();
value += ((small(temp[1]-'0') + 5) + third);
}
for(short i = 70;i<80;i++)//70-80
{
std::stringstream ss;
ss<<i;
temp = ss.str();
value += ((small(temp[1]-'0') + 7) + third);
}
}

short small(short x)
{
switch(x)
{
case 0:
return 0;
case 1:
return 3;
case 2:
return 3;
case 3:
return 5;
case 4:
return 4;
case 5:
return 4;
case 6:
return 3;
case 7:
return 5;
case 8:
return 5;
case 9:
return 4;
case 10:
return 3;
case 11:
return 6;
case 12:
return 6;
case 13:
return 8;
case 14:
return 8;
case 15:
return 7;
case 16:
return 7;
case 17:
return 9;
case 18:
return 8;
case 19:
return 8;
}
}

最佳答案

首先,您需要考虑 John Mashall 的回答。使用字符串的解决方案不是最优的,您可以考虑使用模数 10 提取第二个数字。

您没有添加圆百 100、200、300、400,...您正确地添加了 101、102...,但不是圆百。在添加初始和百(10 个字符)的代码中,您还应该添加 的长度(7)(以及一、二、你...)到值:

if(third>0)
{
third = (small(third) + 10);//10 = and(3) + hundred(7)
value += third - 3; // no need for the "and"
}

如果我应用 John Marshalls 修复(改为使用模数)并应用上面的方法,我会得到正确的结果(将鼠标悬停在下面的框上以查看结果):

21124

关于c++ - 欧拉计划(#17),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7944504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com