简体   繁体   中英

Can someone explain me this recursive method?

This code counts the number 7 of your input. This is the code method:

    public static int count7(int n) {
    if (n == 0) {
        return 0;
    }
    else if (n % 10 == 7) {
        return 1  + count7 (n/10);
    }
    else {
        return count7(n/10);
    }
}

What does the else-if statement and else do? Thank you so much.

if (n == 0) {
    return 0;

There are no 7s in 0, so return 0.

} else if (n % 10 == 7) {

checks if the least significant digit of the number is 7. If that's the case, the total number of 7s is 1 + the number of 7s in the number you get by removing that digit (by dividing the number by 10) :

     return 1  + count7 (n/10);

} else {

If the least significant digit is not 7, the number of 7s is the number of 7s in n/10 :

    return count7(n/10);
}

if (n % 10 == 7)如果余数是 7 让我们举n=17例子n=17所以17%10你会得到 7 所以加 1 意味着你已经找到了 7 如果你还没有找到然后去 else部分,这次通过除以调用它假设这次 n=28 显然这个数字中没有 7 所以它会转到 else if 条件并且它将失败它将转到 else 部分并且它将调用该方法通过将 n 除以 10 进行下一次迭代。

This is a recursive method .

The first if is the base case , ie, if the numbers is 0, then it returns 0.

The else if checks if the digit is 7. If it is, then get the answer to the remaining digits (whether they have any 7s) using the same method, add 1 to it, and return the value.

The last else just removes one digit, and calls the method for the remaining digits.

This method counts the total amount of the digit 7 in a given number.

n % 10 == 7 inspects the least significant digit, and if it equals 7, then add 1 to the sum.

In any case, the algorithm goes on with the other digits by taking n / 10 , which actually removes the least significant digit, and then calls the method recursively. As the number is decreasing with 1 digit with each call and the stop trigger n == 0 makes the method eventually stop, the final returned number counts the sevens in the initial number.

Example

count7(172) = 0 + count7(17) = 0 + 1 + count7(1) = 0 + 1 + 0 = 1

该函数简单地计算数字 7 在任何给定非负整数中出现的总数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM