Project Euler Problem 17 Number letter counts
Problem 17
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.
C++:
#include <iostream> #include <string> using namespace std; const int TWENTY = 20; const int HUNDRED = 28; const int ONE_THOUSAND = 29; string number[] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety", "hundred and", "one thousand"}; int main() { int sum=0, sum2=0; // 1 - 19 sum2 = 0; for(int i=1; i<=19; i++) sum2 += number[i].length(); sum += sum2; // 20 - 99 sum2 = 0; for(int i=20; i<=99; i++) { int d10 = i / 10, d0 = i % 10; sum2 += number[TWENTY + d10 - 2].length(); if(d0 != 0) sum2 += number[d0].length(); } sum += sum2; // 100 - 999 sum2 = 0; for(int i=1; i<=9; i++) { sum2 += (number[i].length() + number[HUNDRED].length() - 1) * 100 - 3; sum2 += sum; } sum += sum2; // 1000 sum += number[ONE_THOUSAND].length() - 1; cout << sum << endl; return 0; }