You can print the results using console.log, but when you go out with return, you will be undefined.

given a non-negative integer, num, repeatedly adds the numbers in each bit until the result is a single digit.

For the sum problem of

leetcode, my idea is to divide the numbers and add them, recursively, and return the numbers less than 10

.

related codes

        var addDigits = function(num) {
            let str = num+=""
            let len = str.split("").length;
            let numTemp = 0
            if(num < 10) {
                console.log(num)//2
                return num
                
            } else {
                for (let i =0; i<len;iPP) {
                    numTemp += parseInt(str.split("")[i], 10)
                }    
                addDigits(numTemp)
                
            }
            
        };
        
    console.log(addDigits(38)//undefined

what result do you expect? What is the error message actually seen?

2undefined,2

May.06,2021

if it is recursive addDigits there is a return


if num < 10 can get the correct result, then entering the recursive, return num just ends the recursive condition and returns ~ the final function does not return a value


the result of the recursive call is not returned. It must be changed from undefined; to the following:


,console

var addDigits = function(num) {
            let str = num+=''
            let len = str.split('').length;
            let numTemp = 0
            for (let i =0; i<len;iPP) {
                    numTemp += parseInt(str.split('')[i], 10)
            }    
            numTemp>=10&&(numTemp=addDigits(numTemp))
            return numTemp
        };
Menu