欧拉项目(#17)
Project Euler (#17)
本文关键字:项目 更新时间:2023-10-16
欧拉项目第17题:
如果数字1到5写成单词:one, two, three, four, five,那么总共有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…正确,但不是整数百位。在添加初始和hundred(10个字符)的代码中,您还应该将hundred(7)(以及one, two, thee,…)的长度添加到值:
if(third>0)
{
third = (small(third) + 10);//10 = and(3) + hundred(7)
value += third - 3; // no need for the "and"
}
如果我应用John Marshalls的修复(使用模数代替)并应用上述内容,我得到正确的结果(将鼠标悬停在下面的框上以查看结果):
<引用类>21124年引用类>第一个错误是
ss.str() = "";
并不是你想的那样。您应该在每个循环中打印出temp
,以检查您添加的是您认为添加到value
的内容。
然后你应该简化这个问题:检查你的程序产生和添加到value
的量是否正确,从1到10,1到20,1到100,1到110,等等。你会发现,如果你的程序被组织好了,你就可以请求任何1到n的和——例如,对于命令行上给出的n,你会更容易调试它。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 无法在 CLion 中构建 C++ 项目
- 运行同一解决方案的另一个项目的项目
- CMake-按正确顺序将项目与C运行时对象文件链接
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 欧拉项目#8答案是大以获得有效答案
- 从链接列表c++中删除一个项目
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 既然存在危险,为什么项目要使用-I include开关
- cmake在我的项目中所需的所有静态库都不成功
- QT通过C++添加映射QML项目
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 在linux上调试巨大的C++项目
- 在其他文件中创建类时在 c++ 项目中不起作用
- 使外部项目可用于find_package CMake
- 在子目录中使用target_sources()命令时用于单元测试(qtest)的项目结构
- 使用外部SDK工具链文件在VisualStudio上生成项目编译错误
- 如何维护资源管理器项目视图中当前可见的项目列表
- 错误-我无法在VS2019中打开新的Qt项目
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗