JavaScript: calculation of the number of occurrences in numbers 1

topic:

  A write function, the input is an unsigned integer, which returns the number of digits in the binary representation of the number '1' (also called Hamming weight ).

Example 1:

Input: 00000000000000000000000000001011

Output: 3

Explanation: 00000000000000000000000000001011 input binary string, a total of three to '1'.

 

This issue is mainly to test the knowledge points:

 

    Numbers beginning with 1,0, js will automatically resolve to octal

    2, a pair of matching record occurrences

 

    Chicken dishes solution:

 var hammingWeight = function (n) {

        var j = 0

        var num = n.toString(2).split('')

        for (var i = 0, len = num.length; i < len; i++) {

            if (num[i] == 1) {  

                j++

            }

        }

        return j

    };

 

    Great God direct solution :( regular get) ps: I did not think of how big God is Great God.

 

  

  var hammingWeight = function (n) {

        return ((n.toString(2)).match(/1/g) || []).length

    };

 

 

 

Author: wang-yi-dong

Link: https: //leetcode-cn.com/problems/number-of-1-bits/solution/javascriptti-jie-by-wang-yi-dong/

Topic link: https: //leetcode-cn.com/problems/number-of-1-bits

Source: stay button (LeetCode)

 

Your support is me going -

Guess you like

Origin www.cnblogs.com/wyd168/p/11564022.html