java – Codingbat- Recursion1- count7

Anyone can program the next question for me (from codingbat – recursion1 – count7)

Given a nonnegative int n, the number of occurrences of 7 is returned as a number, so for example, 717 gets 2 (no cycle) Note that mod (%) is multiplied by 10 to get the rightmost number (126% 10 is 6), and divide by (10) to remove the rightmost number (126 / 10 is 12)

count7(717) → 2
count7(7) → 1
count7(123) → 0

Some solutions include many "rewards" I want to program the problem with 1 "return"

Solution

public int count7(int n) {
public int count7(int n) {
  int counter = 0;

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

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

  return counter + count7(n/10); 
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>