My straightforward solution in JS


  • 5
    S

    Here's my solution using JavaScript. Should be pretty easy to follow. Basically, I keep calculating the sum of squares until I come across one that I've already seen. The nice thing about this approach is that it memoizes all values so if this were used on multiple numbers, in the event that during the process a previously seen number is encountered, an answer can immediately be given.

    var isHappy = function(n) {
        var seen = {};
        while (n !== 1 && !seen[n]) {
            seen[n] = true;
            n = sumOfSquares(n);
        }
        return n === 1 ? true : false;
    };
    
    function sumOfSquares(numString) {
        return numString.toString().split('').reduce(function(sum, num) {
            return sum + Math.pow(num, 2);
        }, 0);
    }

  • 0
    C

    Thank you very much.
    It is my funny solution

    var isHappy = function(n) {
      n = n+'';
      if(n=='1111111')return true
      var m = 0;
      for(var i=0;i<n.length;i++){
        m+=Math.pow(+n[i],2)
      }
      if((m+'').length == 1){
        return m == 1;
      }else{
        return isHappy(m);
      }
    };
    

  • 0
    C

    @chechengpeng I know I am wrong. This is my shame


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.