We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 048791e commit fea064dCopy full SHA for fea064d
Candy-017/README.md
@@ -0,0 +1,33 @@
1
+## 編號:CANDY-017
2
+
3
+### 程式語言:JavaScript
4
5
+#### 題目:計算數字的 2 進位裡有幾個 1
6
7
+範例:
8
9
+```js
10
+5 -> 101 -> 2 個 1
11
+```
12
13
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