首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Codingbat- Recursion1- count7

Codingbat- Recursion1- count7
EN

Stack Overflow用户
提问于 2014-04-17 15:07:58
回答 15查看 19K关注 0票数 3

有人能帮我编写下一个问题(摘自Codingbat- Recursion1- count7)吗?

给定一个非负的int n,,返回occurrences of 7 as a digit的计数,例如717 yields 2. (无循环)。注意,mod (%)乘以10生成rightmost digit (126 % 10 is 6),,而除法(/)减去最右边的数字(126 / 10是12)。

代码语言:javascript
运行
复制
count7(717) → 2
count7(7) → 1
count7(123) → 0

有一些解决办法,其中包括“回报”的数目。我只想用一个“返回”来编程这个问题。

EN

回答 15

Stack Overflow用户

回答已采纳

发布于 2017-06-10 11:58:31

代码语言:javascript
运行
复制
public int count7(int n) {
  int counter = 0;

  if( n % 10 == 7) counter++;

  if( n / 10  == 0)  return counter;

  return counter + count7(n/10); 
}
票数 2
EN

Stack Overflow用户

发布于 2014-07-23 17:38:48

好的,这是我写的解决方案,让我们看看如何只返回一次

代码语言:javascript
运行
复制
public int count7(int n) 
{
    int c = 0;
    if (7 > n)
    {
        return 0;
    }
    else
    {
        if ( 7 == n % 10)
        {
            c = 1;
        }
        else
        {
            c = 0;
        }
    }
    return c + count7(n / 10);  
}

同样,只有一次返回

代码语言:javascript
运行
复制
public int count7(int n) 
{
    return (7 > n) ? 0 : ( ( 7 == n % 10) ? 1 + count7(n / 10) : 0 + count7(n / 10));  
}
票数 6
EN

Stack Overflow用户

发布于 2014-07-02 15:32:39

当然,PFB我的解决方案在JAVA中也是如此

代码语言:javascript
运行
复制
public int count7(int n) {
   if((n / 10 == 0) && !(n % 10 == 7))      //First BASE CASE when the left most digit is 7 return 1
       return 0;     
   else if((n / 10 == 0) && (n % 10 == 7)) //Second BASE CASE when the left most digit is 7 return 0
        return 1;
   else if((n % 10 == 7))   
   //if the number having 2 digits then test the rightmost digit and trigger recursion trimming it there      
       return 1 + count7(n / 10);
   return count7(n / 10);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23136817

复制
相关文章

相似问题

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