From 3bdee5ac6c43b554ee2d9dda65845271d1634a2b Mon Sep 17 00:00:00 2001 From: byol-han Date: Mon, 30 Jun 2025 01:31:50 -0700 Subject: [PATCH] counting bits solution --- counting-bits/byol-han.js | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 counting-bits/byol-han.js diff --git a/counting-bits/byol-han.js b/counting-bits/byol-han.js new file mode 100644 index 000000000..b51c16f66 --- /dev/null +++ b/counting-bits/byol-han.js @@ -0,0 +1,16 @@ +/** + * https://leetcode.com/problems/counting-bits/submissions/1681218194/ + * @param {number} n + * @return {number[]} + */ +var countBits = function (n) { + const ans = []; + for (let i = 0; i <= n; i++) { + // Convert i to binary with i.toString(2) + // Count 1s by splitting into chars, filtering '1', and getting length + const binary = i.toString(2); + const onesCount = binary.split('').filter((bit) => bit === '1').length; + ans.push(onesCount); + } + return ans; +};