Converting a loop into a recursive function

后端 未结 5 1369
挽巷
挽巷 2020-12-18 13:33

I wrote a function yesterday to count the number of \"a\" characters in a string. My teacher told me to refactor the code into a recursive function and I don\'t

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-18 14:10

    Try this:

    function numberOfA(n) {
        return n == "" ? 0 : (n.charAt(0) == "a" ? 1 : 0) + numberOfA(n.substring(1))
    }
    

    Here's how it works:

    • If n is the empty string, return 0 and finish the recursion. This is the base case of the recursion.
    • Else if the character at the first position in the string is an "a" add one, if not add zero and either way advance the recursion by removing the first character from the string. This is the recursive step of the recursion.

    As you can see, every recursive solution must have at least a base case and a recursive step.

提交回复
热议问题