// Brute force solver for the Word Number problem
#include <iostream>
#include <string>
int length_ones[10] = {0,3,3,5,4,5,3,5,5,4}; // "", one, two, three, ...
int length_tens[10] = {0,3,6,6,5,5,5,7,6,6}; // "", ten, twenty, ...
int length_teens[10] = {3,6,6,8,8,7,7,9,8,8}; // ten, eleven, twelve, ...
const char * ones[] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"};
const char * tens[] = {"", "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
const char * teens[] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteeen", "nineteen"};
std::string wordify(long n)
{
if(n < 10) return ones[n];
else if(n < 20) return teens[n-10];
else if(n < 100) return std::string(tens[n/10]) + ones[n%10];
else if(n < 1000) return std::string(ones[n/100]) + "hundred" + wordify(n%100);
else if(n < 1000000) return wordify(n/1000) + "thousand" + wordify(n%1000);
else return wordify(n/1000000) + "million" + wordify(n%1000000);
}
int word_length(long n)
{
if(n < 10) return length_ones[n];
else if(n < 20) return length_teens[n-10];
else if(n < 100) return length_tens[n/10] + length_ones[n%10];
else if(n < 1000) return length_ones[n/100] + 7 + word_length(n%100); // 7 for "hundred"
else if(n < 1000000) return word_length(n/1000) + 8 + word_length(n%1000);
else return word_length(n/1000000) + 7 + word_length(n%1000000);
}
int main()
{
long sumNumbers = 0;
long sumLength = 0;
long i = 1;
const long target = 51000000000;
for(; i < 999999999; i++)
{
sumNumbers += i;
long newSumLength = word_length(i) + sumLength;
if(newSumLength >= target)
break;
sumLength = newSumLength;
}
std::cout << "Sum: " << sumNumbers << std::endl;
std::cout << "The letter is " << wordify(i)[target - sumLength - 1] << std::endl;
return 0;
}
Ly8gQnJ1dGUgZm9yY2Ugc29sdmVyIGZvciB0aGUgV29yZCBOdW1iZXIgcHJvYmxlbQoKI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RyaW5nPgoKaW50IGxlbmd0aF9vbmVzWzEwX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