Converting a loop into a recursive function

后端 未结 5 1356
挽巷
挽巷 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:12

    Well, the basic concept of recursion is solving a problem with a smaller version of itself.

    You have a function, numberOfA which gives you the length of a string(or maybe substring).

    So let's say you have the string "javascript' the first string is at index 2.

    It's logical to say that the number of as in your string is equal to 1 plus the number of as in the entire substring after the first a.

    So what you do, is you add 1 to the number of as in the substring vascript


    So here's some psudocode

    function numA(str)
    {
        var substring = substr(index_of_first_a, str.length - index_of_first_a
        return 1 + numA(substring);
    }
    

提交回复
热议问题