• Status: Solved
• Priority: Medium
• Security: Public
• Views: 1293

# Finding odd digits in a number in JAVA

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....
0
hugonieto
3 Solutions

Commented:
Here's the math part:
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.
0

Author Commented:
Thanks phoffric!

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.
0

Commented:
0

Commented:
In JAVA integer division removes the last digit and n%10 (ie n mod10) gives you the last digit.

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   //ie n is a single digit
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.
0

Commented:
I tried to help with the algorithm. May I suggest that once you understand the algorithm that you write up what you can (even if not recursive), and post the problem code in the Java zone. That is a good place to get specific coding advice.
0

progCommented:
sorry it is c (untested!) but treat it as pseudo code.

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);
}

}
0

Author Commented:
Thank you so much guys! I tried it with all of your sugestions and it worked!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

## Featured Post

Tackle projects and never again get stuck behind a technical roadblock.