Home > other >  Recursive digit sum hackerrank javascript runtime error on 3 tests
Recursive digit sum hackerrank javascript runtime error on 3 tests

Time:10-30

I am trying to solve Recurive Digit Sum, and I actually solved it, but I got 3 runtime errors on large inputs when submitting. I have optimized my code a lot, but still I am getting runtime errors. I have googled and tried every answers/solutions I got on Internet, but they were all wrong, those codes were not able to pass all tests cases. I think my code should be optimized more, but I don't know how.
Here is my code:

function superDigit(n, k) {
    // Write your code here
    if (n < 10) return n
    
    let c = ""
    let i = 0
    if (k && k > 0) {
        while(i < k) {
            c  = n
            i  
        }
    }
    
    return findSum(c === "" ? n : c)
}

function findSum(n) {    
    let sum = 0
    let i = 0
    while(i < n.length) {
        sum  =  n[i]
        i  
    }
    
    if (sum < 10) return sum
    
    return findSum(sum.toString())
}

I am stuck, any help would be appreciated!

CodePudding user response:

It looks to me that your approach works. Below you will also find my take on it: digsum():

function digsum(n){
  return n<10? n :
   digsum(("" n).split("").reduce((a,c)=> a ( c)))
}

function superDigit(n, k) {
// Write your code here
if (n < 10) return n

let c = ""
let i = 0
if (k && k > 0) {
    while(i < k) {
        c  = n
        i  
    }
}

return findSum(c === "" ? n : c)
}

function findSum(n) {    
let sum = 0
let i = 0
while(i < n.length) {
    sum  =  n[i]
    i  
}

if (sum < 10) return sum

return findSum(sum.toString())
}

[123456,6600,888885439].forEach(n=>
 console.log(superDigit(n,1),digsum(n)));

CodePudding user response:

I just optimized my code more, and all test cases are passed.
Note: I am not using any built-in method like reduce, otherwise this code should have been shorter with reduce

function superDigit(n, k) {
    // Write your code here
    
    if (n.length === 1) return n
    
    const nArr = n.split('')
    let sum = 0
    let i = 0
    while(i < nArr.length) {
        sum  =  nArr[i]
        i  
    }
    sum = (sum * k)   ''
    
    return superDigit(sum, 1)
}
  • Related