Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Problem statement: https://leetcode.com/problems/backspace-string-compare/
- *
- * Not a super-efficient solution. There are tricks to do bit-counting that would make this much faster
- * (obviating the need to iterate over each bit in the binary string).
- */
- /**
- * @param {number} n
- * @return {number[]}
- */
- var countBits = function(n) {
- let num = 0;
- const arr = [];
- while (num <= n) {
- arr.push(getOnes(num));
- num += 1;
- }
- return arr;
- }
- function getOnes(num) {
- const binStr = num.toString(2);
- let count = 0;
- for (let i = 0; i < binStr.length; i++) {
- if (binStr[i] == 1) count += 1;
- }
- return count;
- }
Advertisement
Add Comment
Please, Sign In to add comment