One line solution in javascript


  • 0

    Recursive solution. Check if it is even or odd and divide it by 2, keep checking until it is 0

    /**
     * Complex: O(logn)
     * Runtime: 156ms
     * Tests: 600 test cases passed
     * Rank: A
     * Updated: 2015-06-11
     */
    var hammingWeight = function(n) {
        return n === 0 ? 0 : (n % 2) + hammingWeight(~~(n / 2));
    };

  • 0
    T

    hammingWeight=function h(n){return n&&(n&1)+h(n>>>1)}


  • 0

    Wow that's great.
    Can u explain the difference between n>>1 and n>>>1 a little bit?


  • 0
    S

    nice. I did it in one line with

    var hammingWeight = function(n) {
      return Number(n).toString(2).split("").filter((t) => {return t==1}).join("").length;
    };

Log in to reply
 

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