HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Counting number of eights

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
numbercountingeights

Problem

I was doing a few basic Java recursion problems to refresh my memory with recursion (honestly never had to use it in a long, LONG, time), along with using it as a useful way to prepare for any possible interviews for entry level positions. I came upon this problem on codingbat.com:


Given a non-negative int n, compute recursively (no loops) the count
of the occurrences of 8 as a digit, except that an 8 with another 8
immediately to its left counts double, so 8818 yields 4. Note that mod
(%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/)
by 10 removes the rightmost digit (126 / 10 is 12).



  • count8(8) → 1



  • count8(818) → 2



  • count8(8818) → 4




My solution, which was all correct for all the test cases they had is as follows:

public int count8(int n) {
  if(n == 0) {
    return 0;
  } else {

    int count = (n % 10 == 8)? 1: 0;

    //This is testing for adjacent 8s. 
    if(count == 1) {
      int tempN = n;
      tempN = tempN / 10;
      count = (tempN % 10 == 8) ? 2 : 1;
    }

    n = n/10;
    return count + count8(n);
  }
}


I was wondering if anyone could critique this solution, and let me know if this is the best approach, or if there is a better way. I am not a big fan of the if(count == 1) that I created, but that was the only way I could think of to test the presence of an 8 to the left of the current one.

Solution

Another approach is to let the recursive method know if the previous digit was an eight.

public int count8(int n) {
  return count8(n,false)
}

public int count8(int n, boolean lastDigitWasMatch) {
  if(n == 0) {
    return 0;
  } else {

    boolean match = (n % 10 == 8);
    int count = match?(lastDigitWasMatch?2:1):0;
    return count+count8(n/10,match);
  }
}

Code Snippets

public int count8(int n) {
  return count8(n,false)
}

public int count8(int n, boolean lastDigitWasMatch) {
  if(n == 0) {
    return 0;
  } else {

    boolean match = (n % 10 == 8);
    int count = match?(lastDigitWasMatch?2:1):0;
    return count+count8(n/10,match);
  }
}

Context

StackExchange Code Review Q#153364, answer score: 12

Revisions (0)

No revisions yet.