Recursive Digit Sum

  • + 1 comment

    @drzaiusx11 This recursive JavaScript solution has passed all test cases in Node.js:

    JavaScript Solution (with Recursion)

    function superDigit(n, k) {
        n = n.split("").reduce((a, b) => +a + +b) * k + "";
        return (n.length > 1) ? superDigit(n, 1) : n.charAt(0);
    }
    
    • + 1 comment

      can you please explain why you wrote this +a + +b instead of a+b?. i tried running a+b, but it failed.

      • + 0 comments

        Late reply, but the reason this works is: ( +a + +b ) coerces each variable with a unary operator ( + ), to assure the addition of two integers and not the concatination of two strings. Then, the integer is being multiplied by the concat multiplier ( * k ) and converted back to a string ( + "" )