'count number of digit using recursive method

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 program seems not able to count double '8's. Here's the code.

public int count8(int n) {
    boolean flag = false;
    if(n<10)
    {
      if (n==8)
      {
         if(flag == true)
             return 2;
         else 
         { 
             flag = true;
             return 1;
         }
      }
      else 
      {
        flag = false;
        return 0;
      }
    }

    else
       return count8(n%10)+count8(n/10);

}

I was wondering if the last line goes wrong but I don't know how to check it. Looking forward to your help. Thanks!



Solution 1:[1]

Pass the state (is the previous digit eight) to the method:

private static int count8(int n, boolean eight) {
  if (n <= 0)
    return 0;
  else if (n % 10 == 8)
    return 1 + (eight ? 1 : 0) + count8(n / 10, true);
  else
    return count8(n / 10, false);
}

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

Solution 2:[2]

Your flag variable is only local. There's only one time you read it: if (flag == true) and since you never change it's value before that it will always be false.

You make this a lot more complicated than it has to be though. No need for an additional parameter at all.

public int count8(int n)
{
    if (n % 100 == 88) return count8(n/10) + 2;
    if (n % 10 == 8) return count8(n/10) + 1;
    if (n < 10) return 0;
    return count8(n/10);
}

Solution 3:[3]

You can try smth like this:

public int count8(int n) {
    if (n < 10)
        return n == 8: 1 ? 0;

    int count = 0;
    String num = Integer.toString(n);
    int numLength = num.length();

    if (numLength % 2 != 0)
        num += "0";

    if ((num.charAt(numLength / 2) == num.charAt(numLength / 2 - 1)) && (num.charAt(numLength / 2) == "8"))
        count++;

    String left = num.substring(0, numLength / 2);
    int leftInt = Integer.parseInt(left);
    String rigth = num.substring(numLength / 2);
    int rigthInt = Integer.parseInt(rigth);

    return count + count8(leftInt) + count8(rigthInt);
}

Solution 4:[4]

C++

int count8(int n) {
    return n == 0 ? 0 : (n % 10 == 8) + (n % 100 == 88) + count8(n/10);
}

Java & C#

int count8(int n) {
    if (n==0) return 0;
    if(n % 100 == 88)
        return 2 + count8(n / 10);
    if(n % 10 == 8)
        return 1 + count8(n / 10);

    return count8(n / 10);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dmitry Bychenko
Solution 2
Solution 3 Gregory Prescott
Solution 4