Search code examples
javaalgorithmrecursion

Single-Return Recursive Solution to Count Digit '7' in an Integer


I'm seeking assistance with a programming challenge from Codingbat under the section Recursion-1, specifically the count7 problem. The task is to count the occurrences of the digit '7' in a given non-negative integer n, using recursion without loops and limiting the function to a single return statement.

For example:

  • count7(717) should return 2.
  • count7(7) should return 1.
  • count7(123) should return 0.

Details:

  • Using modulo (%) by 10 yields the rightmost digit (for instance, 126 % 10 results in 6).
  • Dividing (/) by 10 removes the rightmost digit (for instance, 126 / 10 becomes 12).

I am aiming for a solution that incorporates these operations in a recursive function with just one return statement. Can anyone help?


Solution

  • public int count7(int n) {
      int counter = 0;
    
      if( n % 10 == 7) counter++;
    
      if( n / 10  == 0)  return counter;
    
      return counter + count7(n/10); 
    }