Skip to content

Commit fea064d

Browse files
committed
update Candy-017
1 parent 048791e commit fea064d

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Candy-017/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
## 編號:CANDY-017
2+
3+
### 程式語言:JavaScript
4+
5+
#### 題目:計算數字的 2 進位裡有幾個 1
6+
7+
範例:
8+
9+
```js
10+
5 -> 101 -> 21
11+
```
12+
13+
```js
14+
function countBits(num) {
15+
let result = 0;
16+
const numBinary = num.toString(2);
17+
for (let i = 0; i < numBinary.length; i++) {
18+
if (Number(numBinary[i]) == 1) {
19+
result += 1;
20+
}
21+
}
22+
return result;
23+
}
24+
25+
// 設定一個變數 result
26+
// 設定一個常數 numbinary 為二進位後的字串
27+
// 寫一個 for 迴圈
28+
// 判斷當值是否為 1, 如果是就加 1 到變數裡面並回傳
29+
30+
console.log(countBits(1234)); // 5
31+
console.log(countBits(1450)); // 6
32+
console.log(countBits(9527)); // 8
33+
```

0 commit comments

Comments
 (0)