LeetCode Js-191. Number of 1 Bits

    LeetCode Js-String

    Write a function that takes an unsigned integer and returns the number of ‘1’ bits it has (also known as the Hamming weight).

    編寫一個函式,且可從一個沒有符號的數列中,回傳符合 '1' 的數量。
    

    Example 1:

    Input: n = 00000000000000000000000000001011
    Output: 3
    Explanation: The input binary string 00000000000000000000000000001011 
                 has a total of three '1' bits.
    

    Example 2:

    Input: n = 00000000000000000000000010000000
    Output: 1
    Explanation: The input binary string 00000000000000000000000010000000 
                 has a total of one '1' bit.
    

    Example 3:

    Input: n = 11111111111111111111111111111101
    Output: 31
    Explanation: The input binary string 11111111111111111111111111111101 
                 has a total of thirty one '1' bits.
    

    Solution:
    1. 宣告 count 次數為 0。
    2. 宣告 nums 為 n.toString 二進制的字串,且將陣列中的每個數值分割為單一元素。

    Ex. Input = 3
    toString(2) = 00000000000000000000000000001011
    toString(2).split("") = 
    [
      '0', '0', '0', '0', '0', '0',
      '0', '0', '0', '0', '0', '0',
      '0', '0', '0', '0', '0', '0',
      '0', '0', '0', '0', '0', '0',
      '0', '0', '0', '0', '1', '0',
      '1', '1'
    ]
    

    3. 運用「for in」將每個元素皆除以2,如果剩餘1,則 count++。
    4. 回傳 count 次數。

    Code:

    var hammingWeight = function(n) {
      let count = 0
      let nums = n.toString(2).split("");
    
      for (let num in nums) {
        if (nums[num] % 2 === 1) {
          count ++
        }
      }
      return count
    };
    

    FlowChart:
    Example 1

    Input: n = 00000000000000000000000000001011
                                           1 23 
    Output count = 3
    

    Example 2

    Input: n = 00000000000000000000000010000000
                                       1
    Output count = 1
    

    Example 3

    Input: n = 11111111111111111111111111111101
               1---------------------------->31
    Output count = 31
    

    .toString(2):

    const x = 6;
    console.log(x.toString(2));       // displays '110'
    

    .split():

    const str = 'The quick brown fox jumps over the lazy dog.';
    
    const words = str.split(' ');
    console.log(words[3]);
    // expected output: "fox"
    
    const chars = str.split('');
    console.log(chars[8]);
    // expected output: "k"