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.
Input: n = 00000000000000000000000000001011
Output: 3
Explanation: The input binary string
00000000000000000000000000001011 has a total of three '1' bits.
Input: n = 00000000000000000000000010000000
Output: 1
Explanation: The input binary string
00000000000000000000000010000000 has a total of one '1' bit.
Input: n = 11111111111111111111111111111101
Output: 31
Explanation: The input binary string
11111111111111111111111111111101 has a total of thirty one '1' bits.
숫자를 2진수로 변환할 때 앞자리 0을 남겨두어야 한다.
문제는.. 이미지와 같이 n을 그대로 사용하려면 일부 숫자가 (unsigned integar)이 사라져버린다.
toString에 매개변수를 전달해 2진수부터 36진수까지 표현가능하다.
let baseTenInt = 10;
console.log(baseTenInt.toString(2));
// "1010"이 출력된다
let bigNum = BigInt(20);
console.log(bigNum.toString(2));
// "10100"이 출력된다
toString을 사용하면 2진수를 그대로 표현하기 때문에 그대로 유효한 숫자를 가져올 수 있다.
/**
* @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을 반환한다.
124 ms, faster than 14.54% of JavaScript online submissions for Number of 1 Bits.
40.3 MB, less than 32.42% of JavaScript online submissions for Number of 1 Bits.