[leetCode] 191. Number of 1 Bits

5216 ワード

🔵 Description


Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).
Note:
Note that in some languages, such as Java, there is no unsigned integer type. In this case, the input will be given as a signed integer type. It should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 3, the input represents the signed integer. -3.

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


数字を2進数に変換する場合は、前列のゼロを残します.

問題は...画像のようにnを使用すると、いくつかの数字(unsigned integar)が消えます.

toString


パラメータをtoStringに渡し、バイナリから36進数まで表現できます.
let baseTenInt = 10;
  console.log(baseTenInt.toString(2));
  // "1010"이 출력된다

let bigNum = BigInt(20);
  console.log(bigNum.toString(2));
  // "10100"이 출력된다

TOStringを使用すると、バイナリ数を直接表すことができるので、有効な数値を直接インポートできます.
/**
 * @param {number} n - a positive integer
 * @return {number}
 */
var hammingWeight = function(n) {
    return n.toString(2).match(/1/g)?.length || 0
};
n.toString(2)で有効な数値を取得した後、1がある場合は長さのみを返し、ない場合は0を返します.

🔵 Result


Runtime


124 ms, faster than 14.54% of JavaScript online submissions for Number of 1 Bits.

Memory Usage


40.3 MB, less than 32.42% of JavaScript online submissions for Number of 1 Bits.

Reference

  • https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
  • https://egg-programmer.tistory.com/292
  • https://velog.io/@ansrjsdn/LeetCode-Power-Of-Two-JavaScript