n = 12345

n/10 = 1234 (integer truncation)

(n/10)*10 = 12340

n - 12340 = 12345 - 12340 = 5, odd because 5 mod 2 == 1

Now call the recursive method again with 1234 and keep count of number of odd digits.

Solved

Posted on 2012-09-03

Hello guys!

I'm trying to write a recursive method that computes the number of digits in a number with JAVA code. I need some help on how to start or how to write it..... I know basic java but Im lost on how to make this happen....

I'm trying to write a recursive method that computes the number of digits in a number with JAVA code. I need some help on how to start or how to write it..... I know basic java but Im lost on how to make this happen....

7 Comments

n = 12345

n/10 = 1234 (integer truncation)

(n/10)*10 = 12340

n - 12340 = 12345 - 12340 = 5, odd because 5 mod 2 == 1

Now call the recursive method again with 1234 and keep count of number of odd digits.

I will try it.... I know how to do this with a for loop or any other loop but with a recursive method..... I'm little lost! But thank you for the help! I will try to write your suggestion.

Also n%2 =0 if n =even, n%2=1 if n is odd.

So recursively the function numOddDigits(n) mathematially is given by

if n/10 = 0

numOddDigits(n) = n%2 //

else

numOddDigits(n) = numOddDigits(n/10) + (n%10)%2

Now you have to code that mathematical definition up as a recursive Java function

I have given you a start.

int odd_digits(int x)

{

int next;

int odd;

next = x / 10;

//mod operation, as suggested by previous posts

odd = (x - next * 10) % 2;

if (next == 0)

{

return odd;

}

else

{

//Recursive function call, add the odds we counted here (0 or 1) to the count for the rest of the string

return odd + odd_digits(next);

}

}

By clicking you are agreeing to Experts Exchange's Terms of Use.

Title | # Comments | Views | Activity |
---|---|---|---|

advance java | 4 | 35 | |

array220 challenge | 8 | 30 | |

strCount chalenge | 3 | 34 | |

maven project clean install and build and adding as war web plugin | 4 | 26 |

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**12** Experts available now in Live!