Problem 17 on project euler states:
If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?
NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of “and” when writing out numbers is in compliance with British usage.
I have looked over my code many times and cant find why it isn’t solving it correctly, any help would be greatly appreciated, thanks
`#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;
}
}
First you need to consider John Mashall’s answer. The solution using strings is not optimal, you might consider extract the second digit using modulus 10 instead.
You aren’t adding the round hundreds 100, 200, 300, 400, … you add 101, 102, … correctly but not the round hundreds. Inside your code that add the initial and hundred (10 characters) you should also add the length of hundred (7) (and one, two, thee, …) to the value:
If I apply John Marshalls fix (using modulus instead) and apply the above I get the correct result of (hover mouse over box below to see result):