You need to write a function that takes a number, and adds the square of each digit until it becomes 1, unless of course it is possible with this number. For example:

x = 23 -> 2 ^ 2 + 3 ^ 2 = 13 -> 1 ^ 2 + 3 ^ 2 = 10 -> 1 ^ 2 + 0 ^ 2 = 1 -> true

x = 22 -> 2 ^ 2 + 2 ^ 2 = 8 -> false

Numbers can be different, for example, 0, 1, 12, 123, 1234 ... If such a number is given that at the end becomes 1, then let it return true, and if not, false. There are such numbers that will endlessly repeat the action, then, when in one part the same numbers will be repeated. In the current case too, empty returns false. (Do not use prototype.) In my examples, the codes only do it once. Probably you need to do a while loop (For example: while (x! = 1) {...}), but I don’t know how.

code 1

function solution(x) { let s=0; x = x.toString().split(''); for (let i=0; i<x.length; i++) { s += Math.pow(x[i],2); } if (s==1) { return true } return false } console.log(solution(23)); 

code 2

 function solution(x) { let y; y=(x + '').split('') .map(b => parseInt(b)) .reduce((a,b) => a += b * b, 0); if (y==1) { return true } return false } console.log(solution(23)); 
  • Possible duplicate question: Integration of numbers, until it becomes 1 - Yaant
  • And what did not suit the answers to the previous question? - Yaant
  • so, as I study, the previous answers were not so clear to me, this time the answer was absolutely clear) - Tyom Arshakyan February
  • I was thinking of deleting the previous one, but I read the rules about deleting the question, and asked a new one. - Tyom Arshakyan

1 answer 1

You generally have the correct logic to solve such a problem, the only thing is that if you don’t know in advance the number of iterations that you need to perform, then it makes sense to use a recursive approach indicating the condition when you need to complete the repeated function call:

  function test(value) { if (value.toString().length == 1) { if (value == 1) { console.log(value); return true; } else { console.log(value); return false; } } value = value.toString().split(""); value = value .map(e => Number(e) * Number(e)) .reduce((accum, e) => accum + e); return test(value); } test(23); 

  • Thank you so much - Tyom Arshakyan