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.
import java.util.Vector;
class runner
{
@SuppressWarnings("serial")
static Vector map = new Vector(){{
add(new Integer[]{1, 3}); add(new Integer[]{2, 3}); add(new Integer[]{3, 5}); add(new Integer[]{4, 4}); add(new Integer[]{5, 4}); add(new Integer[]{6, 3}); add(new Integer[]{7, 5}); add(new Integer[]{8, 5}); add(new Integer[]{9, 4});
add(new Integer[]{10, 3}); add(new Integer[]{11, 6}); add(new Integer[]{12, 6}); add(new Integer[]{13, 8}); add(new Integer[]{14, 8}); add(new Integer[]{15, 7}); add(new Integer[]{16, 7}); add(new Integer[]{17, 9}); add(new Integer[]{18, 8}); add(new Integer[]{19, 8});
add(new Integer[]{20, 6}); add(new Integer[]{30, 6}); add(new Integer[]{40, 5}); add(new Integer[]{50, 5}); add(new Integer[]{60, 5}); add(new Integer[]{70, 7}); add(new Integer[]{80, 6}); add(new Integer[]{90, 6});
add(new Integer[]{100, 7}); add(new Integer[]{1000, 8});
}
};
public static void main (String[] args) throws java.lang.Exception
{
long time = System.currentTimeMillis();
int sum = 0; int n = 1000;
for(int i = 1; i<= n; i++){
boolean BRITISH_AND = false;
int cur = i;
int length = 0;
for(int j = map.size()-1; j>-1; j--){
if(cur == 0) break;
Integer[] mapcur = map.elementAt(j);
int counter = 0;
if(mapcur[0] >= 100){//1000, 100
while(cur > 0 && mapcur[0] <= cur){
counter++;
cur -= mapcur[0];
}
if(counter > 0){
length += mapcur[1];//Add the base number 1000, 100
//Add the counter value
for(int z = 0; z100
if(cur > 0){
BRITISH_AND = true;
}
}
}else{//Normal Number
if(mapcur[0] <= cur){
length += mapcur[1];
cur -= mapcur[0];
}
}
}
if(BRITISH_AND) length += 3;
sum += length;
}
System.out.println(sum);
System.out.println("time: "+(System.currentTimeMillis() - time));
}
}