DAY 12
0

# 今日kata

Write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.

``````數字1234 二進位表示為10011010010，其中出現5次1，結果需回傳5
The binary representation of 1234 is 10011010010, so the function should return 5 in this case
``````

## 構想&解法

``````var countBits = function(n) {
return n.toString(2).split('').filter(item=>item>0).length
};
``````

``````(1234).toString(2)="10011010010"
``````

``````"10011010010".split('')=["1", "0", "0", "1", "1", "0", "1", "0", "0", "1", "0"]

["1", "0", "0", "1", "1", "0", "1", "0", "0", "1", "0"].filter(item->item>0)=["1", "1", "1", "1", "1"]
``````

## 其他解法觀摩

``````countBits = n => n.toString(2).split('0').join('').length;
``````

``````function countBits(n) {
for(c=0;n;n>>=1)c+=n&1
return c;
}
``````

• `>>``&` 都屬於位元運算子，肯定充分使用了位元的概念來解題
• `>>` a>>b，將a的二進位表示法右移 b (< 32) 位元，拋棄被移出的位元。
``````a = 8 // 1 0 0 0
a>>1  // 0 1 0 0  =4
a>>1=4 即是將數字8以位元表示後，往右移１位元
``````

For loop解釋:

`````` for(c=0;n!=0;n=n>>1){
c=c+(n&1)
}
``````
• 初始狀態宣告c=0，c用來計算1出現的次數(count)
• loop執行的終止條件為`n不為0` (0:false; 1:true)
• n和1做位元比較 (當最右邊的位元為1時，c+1)
• 每執行完一次，n>>1 (轉為位元表示並右移一位元)

Ex:位元運算

``````// & 位元AND
// 3 = 0 1 1
// 1 = 0 0 1
// &:當對應位元皆為1時，回傳1
// 3&1 = 0 0 1

// >> 位元右移
// 3>>1
// 3 = 0 1 1
// 3>>1 = 0 0 1
``````

n和1做`&位元運算`，如果n的最右側位元等於1，count數加1。接著n右移一位元，繼續和1做`&位元運算`，n一直一直往右移一位元，直到n=0。