简体   繁体   English

有人可以向我解释这种递归方法吗?

[英]Can someone explain me this recursive method?

This code counts the number 7 of your input.此代码计算您输入的数字 7。 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? else-if 语句和 else 有什么作用? Thank you so much.非常感谢。

if (n == 0) {
    return 0;

There are no 7s in 0, so return 0. 0 中没有 7,所以返回 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) :检查数字的最低有效数字是否为 7。如果是这种情况,则 7 的总数是 1 + 通过删除该数字(通过将数字除以 10)得到的数字中的 7 的数量:

     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 :如果最低有效位不是 7,则 7s 的数量是 n/10 中 7s 的数量:

    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.第一个if基本情况,即如果数字为 0,则返回 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. else if检查数字是否为 7。如果是,则使用相同的方法获取剩余数字的答案(是否有任何 7),将其加 1,并返回值。

The last else just removes one digit, and calls the method for the remaining digits.最后一个 else 只是删除一个数字,并调用剩余数字的方法。

This method counts the total amount of the digit 7 in a given number.此方法计算给定数字中数字 7 的总数。

n % 10 == 7 inspects the least significant digit, and if it equals 7, then add 1 to the sum. n % 10 == 7检查最低有效数字,如果等于 7,则将总和加 1。

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.无论如何,该算法通过取n / 10继续处理其他数字,这实际上删除了最低有效数字,然后递归调用该方法。 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.由于每次调用时数字减少 1 位,并且停止触发器n == 0使方法最终停止,最终返回的数字计算初始数字中的 7。

Example例子

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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