简体   繁体   中英

Digital Root exercise on Javascript

I'm having some trouble trying to do a digital root exercise on Javascript.

Here's my code:

function digital_root(n) {
    var sNumero = n.toString();
    var sum = 0;

    for(i = 0 ; i < sNumero.length; i++){
        sum += parseInt(sNumero[i]);
    }

    if(sum > 9){
        digital_root(sum);
    }
    return sum;
}

When I try to input 456 to 'n', the function gives 15 as the return. The expected is 6. I don't know why this is happening.

To help you guys understand my problem, here's the exercise:

"A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers."

You forgot a return:

if(sum > 9){
    return digital_root(sum); // <-- here
}

You can add a return statement here on

 function digital_root(n) { var sNumero = n.toString(); var sum = 0; for (i = 0; i < sNumero.length; i++) { sum += parseInt(sNumero[i]); } if (sum > 9) { return digital_root(sum); // missing return here } return sum; } console.log(digital_root(456)) 

OR add a new variable to capture the final result before returning.

 function digital_root(n) { var sNumero = n.toString(); var sum = 0; var final_result; // introduce new variable to hold recursive sum for (i = 0; i < sNumero.length; i++) { sum += parseInt(sNumero[i]); } final_result = sum; // assign sum to final_result variable if (sum > 9) { final_result = digital_root(sum); } return final_result; // return final_result } console.log(digital_root(456)) 

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