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.
Solution:
we generate each word in string first and then add the sum of length of each word.
Java code:
Solution:
we generate each word in string first and then add the sum of length of each word.
Java code:
public class Prob17 { static String unitdo[] = {"", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; static String tens[] = {"","Ten","Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty","Ninety"}; public static int digit_counter(int a) { int digit_count = 0 ; while(a>0) { a=a/10; digit_count++; } return digit_count++; } public static String wordGen(int a) { String numWord = ""; int digits = digit_counter(a); while(digits >0) { switch(digits) { case 1: case 2: if(a < 20) { numWord+=unitdo[a]; digits = 0; } else if(a >=20 ) { numWord+= tens[a/10]; a=a%10; if(a ==0) digits = 0; else digits--; } break; case 3: numWord+=unitdo[a/100]; a=a%100; if(a%100 == 0) { numWord+="Hundred"; digits = 0; } else { numWord+="HundredAnd"; digits--; } break; case 4: numWord+=unitdo[a/1000]; a=a%1000; numWord+="thousand"; if(a%1000 ==0) digits = 0; else digits--; break; } } return numWord; } public static void main(String[] args) { int sum = 0; String a = ""; for(int i =1 ; i< =1000; i++) { a = wordGen(i); System.out.println(a); sum= sum+a.length(); } System.out.println(sum); } }
public static int digit_counter(int a)
ReplyDelete{
int digit_count = 0;
while (a > 0)
{
a = a / 10;
digit_count++;
}
return digit_count++;
}
I din't understand this code pls help.
Digit count is the number of digits in the given number.
DeleteEg. 123 gives three.
Method goes like thsi:
a = 123
a=a/10 => a = 12, digitcount=1;
a=a/10 => a=1, didgitcount = 2;
a = a/10 => a=0, digitcount = 3;
--------------------------------
Have a look at my blog and check if useful:
http://thechaithanya.blogspot.com