递归地将8的出现计数为给定数字中的数字

时间:2016-10-13 07:59:15

标签: recursion count numbers digit

给定非负int n,递归计算(无循环)8次出现的计数作为一个数字,除了8与另一个8紧接在其左边计数加倍,所以8818得到4.注意该mod (%)乘以10得到最右边的数字(126%10是6),而除(10)除去最右边的数字(126/10是12)。

我尝试了,我的代码在下面。还请让我知道我在代码中做错了什么。提前谢谢了!!忽略main()。

count8(8)→1

count8(818)→2

count8(8818)→4

public int count8(int n) {

  int cd=0,pd=0,c=0;  // cd for current digit, pd for previous digit,c=count

  if(n==0)           // base condition
    return 0;

  cd = n%10;       // finding the rightmost digit

  if(cd==8)// if rightmost digit id 8 then
  {
    c++;

    n=n/10;// moving towards left from rightmost digit

    if(n!=0)
      pd=n%10;//second rightmost digit(similarly as secondlast digit)

    if(cd==8 && pd==8)// if rightmost and second rightmost equals 8, double c
      c=c*2;
  }     
  else         // if cd not equals 8 then
    c=0;

  return c + count8(n/10);//adding count and recursively calling method  
}

            Expected    Run     
count8(8) → 1             1 OK  
count8(818) → 2           2 OK  
count8(8818) → 4          3 X   
count8(8088) → 4          3 X   
count8(123) → 0           0 OK  
count8(81238) → 2         2 OK  
count8(88788) → 6         4 X   
count8(8234) → 1          1 OK  
count8(2348) → 1          1 OK  
count8(23884) → 3         2 X   
count8(0) → 0             0 OK  
count8(1818188) → 5       4 X   
count8(8818181) → 5       4 X   
count8(1080) → 1          1 OK  
count8(188) → 3           2 X   
count8(88888) → 9         5 X   
count8(9898) → 2          2 OK  
count8(78) → 1            1 OK  

4 个答案:

答案 0 :(得分:0)

我将其简化一点

public int count8(int number, bool prevWas8 = false) 
{
    int num8s = 0;

    if( number == 0) //base case
        return 0;

    if( number%10 == 8) //we found an 8!
        num8s++;

    if (prevWas8 && num8s > 0) // we found two 8's in a row!
        num8s++;

    return num8s + count8(number/10, num8s>0);
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

  }
  else{
    if (n%10==8 && (n/10)%10==8){
      c+=2;
    }
    else if (n%10==8 && (n/10)%10!=8){
      c++;
    }
  }
  return c+count8(n/10);
}

答案 3 :(得分:0)

如果您想简单:

public int count8(int n) {

    return (n < 8) ? 0 : ((n % 10 == 8) ? ((n % 100 == 88) ? 2 : 1) : 0) + count8(n / 10);
}