mystery1
method
public static int countOddDigits(int n)
{
if(n == 0)
return 0;
if(n % 2 == 1)
return 1 + countOddDigits(n / 10);
else
return countOddDigits(n / 10);
}
The method counts and returns the number of odd digits in its parameter n
.
The base case is n == 0
. The method returns 0 because 0 has 0 odd digits.
In both the if
and else
, the method is called with n / 10
, which is n
without its last (least significant, rightmost) digit.
During 1 step, the method checks if n
is odd (n % 2 == 1
). If n
is odd, it adds 1 to the result of the recursive call. If n
is not odd (even), it does not add 1. Adding 1 to the result each time something is true means the method is counting something. It adds 1 when the digit is odd (see below), so it is counting the number of odd digits.
A common mistake is thinking that the method adds 1 to each odd digit, making the digit even. The method isn’t adding 1 to n / 10
or n % 10
. The method is adding 1 to the result of the recursive call with n / 10
.
The conditional statement could be written as:
if((n % 10) % 2 == 1)
The last digit of n
is what determines if n is odd.