Aditya kumar - 2 years ago 76

Java Question

I want to calculate the no of letters in words from 1 to 100. for example....

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.

for which I have written the following code...

`public static int helper(int a){`

String ones[]= {"","one","two","three","four","five","six","seven","eight","nine","ten",

"eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen"

,"eighteen","nineteen"};

String tens[]= {"","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"};

if(a<20){

return ones[a].length();

}

else

return tens[a/10].length();

}

public static int countLetters(int a){

if(a==100)

return 10;

else if(a<20){

return helper(a);

}

else{

return helper((a/10)*10)+ helper(a%10);

}

}

The main function looks like

`public static void main(String[] args) {`

// TODO Auto-generated method stub

int result=0;

for(int i=1;i<=100;i++){

result+=countLetters(i);

}

System.out.println(result);

}

The correct answer for this problem is

`864`

`String ones[]`

`" "`

`result`

`872`

`864`

`""`

Is there any logical aspect with respect to strings or string arrays for this problem ?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

It only happens when you have the `" "`

in the `ones`

array.

If you have 20, you get the length of `"twenty"`

+ the length of `helper(a%10)`

which is `helper(0)`

, which returns the length of `" "`

. So you get the length of `"twenty"`

+ the length of `" "`

.

This happens for 20, 30, 40, 50, 60 ,70 ,80 and 90. 8 times. That's why you see the 872.

The easiest fix is just making the first string `""`

, like you did, but this would work too:

```
// return helper((a/10)*10)+ helper(a%10);
return helper((a/10)*10) + (a%10 == 0 ? 0 : helper(a%10));
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**