fork download
  1. // Brute force solver for the Word Number problem
  2.  
  3. #include <iostream>
  4. #include <string>
  5.  
  6. int length_ones[10] = {0,3,3,5,4,5,3,5,5,4}; // "", one, two, three, ...
  7. int length_tens[10] = {0,3,6,6,5,5,5,7,6,6}; // "", ten, twenty, ...
  8. int length_teens[10] = {3,6,6,8,8,7,7,9,8,8}; // ten, eleven, twelve, ...
  9.  
  10. const char * ones[] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
  11. const char * tens[] = {"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
  12. const char * teens[] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteeen", "nineteen"};
  13.  
  14. std::string wordify(long n)
  15. {
  16. if(n < 10) return ones[n];
  17. else if(n < 20) return teens[n-10];
  18. else if(n < 100) return std::string(tens[n/10]) + ones[n%10];
  19. else if(n < 1000) return std::string(ones[n/100]) + "hundred" + wordify(n%100);
  20. else if(n < 1000000) return wordify(n/1000) + "thousand" + wordify(n%1000);
  21. else return wordify(n/1000000) + "million" + wordify(n%1000000);
  22. }
  23.  
  24. int word_length(long n)
  25. {
  26. if(n < 10) return length_ones[n];
  27. else if(n < 20) return length_teens[n-10];
  28. else if(n < 100) return length_tens[n/10] + length_ones[n%10];
  29. else if(n < 1000) return length_ones[n/100] + 7 + word_length(n%100); // 7 for "hundred"
  30. else if(n < 1000000) return word_length(n/1000) + 8 + word_length(n%1000);
  31. else return word_length(n/1000000) + 7 + word_length(n%1000000);
  32. }
  33.  
  34. int main()
  35. {
  36. long sumNumbers = 0;
  37. long sumLength = 0;
  38. long i = 1;
  39.  
  40. const long target = 51000000000;
  41.  
  42. for(; i < 999999999; i++)
  43. {
  44. sumNumbers += i;
  45. long newSumLength = word_length(i) + sumLength;
  46. if(newSumLength >= target)
  47. break;
  48.  
  49. sumLength = newSumLength;
  50. }
  51.  
  52. std::cout << "Sum: " << sumNumbers << std::endl;
  53. std::cout << "The letter is " << wordify(i)[target - sumLength - 1] << std::endl;
  54.  
  55. return 0;
  56. }
  57.  
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout

Standard output is empty