首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归计数8在给定数字中的数字。

递归计数8在给定数字中的数字。
EN

Stack Overflow用户
提问于 2016-10-13 07:59:14
回答 4查看 4.2K关注 0票数 0

给定一个非负整数,递归地(没有循环)计算出现的8的计数为一个数字,除了一个8和另一个8紧接在它的左边计数双倍,所以8818产生4。注意,mod (%)由10产生最右边的数字(126 % 10是6),而除以(/) 10移除最右边的数字(126 / 10是12)。

我尝试过,我的代码如下。也请让我知道我在代码中做错了什么。非常感谢!!忽略main()

count8(8)→1

count8(818)→2

count8(8818)→4

代码语言:javascript
复制
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  
}
代码语言:javascript
复制
            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  
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-10-15 18:03:08

我会把它简化一点

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2017-03-07 17:34:43

代码语言:javascript
复制
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);
}
票数 0
EN

Stack Overflow用户

发布于 2019-01-09 17:22:32

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40015379

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档