LeetCode 191. Number of 1 Bits
題目
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.
翻譯
給一個整數,找出這個整數有幾個'1',例如11用32-bit表示 '00000000000000000000000000001011',總共有3個1,return 3
思路
這題不考慮效能的話只要收先將將數字n轉為2進位字串,然後跑迴圈找出有多少1。
解題
/**
* @param {number} n - a positive integer
* @return {number}
*/
var hammingWeight = function(n) {
var count = 0 ;
// n轉為二進位
var ary = n.toString(2).split("");
for(var i in ary){
if(ary[i] % 2 ==1){
count++;
}
}
return count;
};