简体   繁体   中英

Codewars problem 'Happy numbers' how can i make some changes on my code to make it works?

I am working Codewars problem' Happy Numbers ' here is the link https://www.codewars.com/kata/happy-numbers-5/train/javascript Here is the problem, when I am running the code when n > 98 the maximum call stack size is reached. How can I make some changes on my code to fix this problem?

function happyNumbers(x){
  var res = [];
  for (let i = 1; i <= x; i++){
    var str = [];
    if (helper(str,i)){res.push(i)}
  }
  return res
}

function helper(str,n){
  var num = 0;
  if (n === 1){return true}
  if (str.indexOf(n) > -1){return false}
  str.push(n);
  if (n.toString().length === 1){num = Math.pow(n,2).toString()}
  if (n.toString().length >= 2){
    num = n.toString().split('')
    .reduce((a,b) => Math.pow(a,2)+ Math.pow(b,2)).toString();
  }
  return helper(str,Number(num))
}

Maybe some more simplyfing would help by

  • using a Set for visited value to prevent circular loop which never ends ( Memoization ),
  • taking numerical values at all, only for splitting into single digits, a string is taken,
  • summing up by using a simple multiplication,
  • now some exit function:
    • check if sum is 1 , exit the function with true ,
    • check if sum is already visited and if so, exit with false ,
  • return by calling the function again with sum and updated set visited with sum .

 function happyNumbers(x, visited = new Set) { var sum = 0, value; for (value of String(x)) sum += value * value; if (sum === 1) return true; if (visited.has(sum)) return false; return happyNumbers(sum, visited.add(sum)); } console.log(happyNumbers(123)); 

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