有人能帮我编写下一个问题(摘自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)。
count7(717) → 2
count7(7) → 1
count7(123) → 0
有一些解决办法,其中包括“回报”的数目。我只想用一个“返回”来编程这个问题。
发布于 2017-06-10 11:58:31
public int count7(int n) {
int counter = 0;
if( n % 10 == 7) counter++;
if( n / 10 == 0) return counter;
return counter + count7(n/10);
}
发布于 2014-07-23 17:38:48
好的,这是我写的解决方案,让我们看看如何只返回一次
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);
}
同样,只有一次返回
public int count7(int n)
{
return (7 > n) ? 0 : ( ( 7 == n % 10) ? 1 + count7(n / 10) : 0 + count7(n / 10));
}
发布于 2014-07-02 15:32:39
当然,PFB我的解决方案在JAVA中也是如此
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);
}
https://stackoverflow.com/questions/23136817
复制相似问题