Approach
In this problem, I thought I can make my own word speller, which might be useful later on to me. The logic is pretty simple and it uses recursion. It works in this way:
- For 1 to 19 we actually explicitly give number names.
- For 20 to 99, we split the spelling into two parts, e.g. for 23, we take 20 from already given value and recursively use spell for 3. We also make sure, if second part is empty, we don’t end up in Twenty zero, rather make no call.
- Similarly we can add more digits – hundreds, thousands and so on.
Code
long mSum = 0;
for (int i = 1; i <= 1000; i++) {
String x = spell(i);
x = x.replaceAll("s|-", "");
mSum += x.length();
}
return mSum;
public static String spell(int i) { // current limit 0-9999
final String[] ones = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };
final String[] tens = { "twenty", "thirty", "fourty", "fifty", "sixty", "seventy", "eighty", "ninety" };
if (0 <= i && i <= 19) {
return ones[i];
} else if (20 <= i && i <= 99) {
return tens[(i / 10) - 2] + ((i % 10 == 0) ? "" : "-" + spell(i % 10));
} else if (100 <= i && i <= 999) {
return spell(i / 100) + " hundred" + ((i % 100 != 0) ? " and " + spell(i % 100) : "");
} else if (1000 <= i && i <= 9999) {
return spell(i / 1000) + " thousand " + ((i % 1000 != 0) ? spell(i % 1000) : "");
}
throw new IllegalArgumentException("Out Of Range");
}
Result: Answer is 21124, Time taken 0.148 seconds