Number letter counts : Problem 17 : Project Euler
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?
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.
JAVA CODE
import java.util.*;
public class NumberLetterCount {
public static void main(String[] args) {
ToWords numbObject = new ToWords();
for(int i = 1; i <=1000; i++) {
numbObject.toWord(i);
}
System.out.println("Letters used:"+numbObject.totalLetterCount());
}
}
class ToWords {
public void toWord(int numb) {
this.number = numb;
this.word = "";
String temp = "";
temp +=number;
switch(temp.length()) {
case 1:
word = oneTwoDigit[number-1];
break;
case 2:
if ( number <= 20)
word = oneTwoDigit[number-1];
else {
if ( (temp.charAt(1)-48) == 0 )
word += tens[(temp.charAt(0)-48)-1];
else
word += tens[(temp.charAt(0)-48)-1]+ " "+oneTwoDigit[(temp.charAt(1)-48)-1];
}
break;
case 3:
if ( (temp.charAt(1)-48) == 0 && (temp.charAt(2)-48) == 0)
word += hundreds[(temp.charAt(0)-48)-1];
else if ( (temp.charAt(2)-48) == 0 )
word += hundreds[(temp.charAt(0)-48)-1]+" and "+tens[(temp.charAt(1)-48)-1];
else {
if ( (temp.charAt(1)-48) == 0 )
word += hundreds[(temp.charAt(0)-48)-1]+" and "+oneTwoDigit[(temp.charAt(2)-48)-1];
else
if ( (temp.charAt(1)-48) == 1 )
word += hundreds[(temp.charAt(0)-48)-1]+" and "+oneTwoDigit[(temp.charAt(2)-48)-1+10];
else
word += hundreds[(temp.charAt(0)-48)-1]+" and "+tens[(temp.charAt(1)-48)-1]+"-"+oneTwoDigit[(temp.charAt(2)-48)-1];
}
break;
case 4:
word = "One Thousand";
break;
}
System.out.println(number+" in words: "+word);
lettersCount(word);
}
private void lettersCount(String word) {
for( int i = 0; i < word.length(); i++ )
if (word.charAt(i) == ' ' || word.charAt(i) == '-')
continue;
else
letterCount +=1;
}
public int totalLetterCount() {
return letterCount;
}
private String[] oneTwoDigit = {"One","Two","Three","Four","Five","Six","Seven",
"Eight","Nine","Ten","Eleven","Twelve",
"Thirteen","Fourteen","Fifteen","Sixteen",
"Seventeen","Eighteen","Nineteen","Twenty"};
private String[] tens = {"Ten","Twenty","Thirty","Forty","Fifty","Sixty",
"Seventy","Eighty","Ninety"};
private String[] hundreds = {"One Hundred","Two Hundred","Three Hundred","Four Hundred","Five Hundred",
"Six Hundred","Seven Hundred","Eight Hundred","Nine Hundred"};
private int number;
private int letterCount = 0;
private String word;
}
No comments:
Post a Comment