micahbales

338. Counting Bits

Oct 18th, 2023 (edited)
716
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /**
  2. * Problem statement: https://leetcode.com/problems/backspace-string-compare/
  3. *
  4. * Not a super-efficient solution. There are tricks to do bit-counting that would make this much faster
  5. * (obviating the need to iterate over each bit in the binary string).
  6. */
  7.  
  8. /**
  9.  * @param {number} n
  10.  * @return {number[]}
  11.  */
  12. var countBits = function(n) {
  13.     let num = 0;
  14.     const arr = [];
  15.     while (num <= n) {
  16.         arr.push(getOnes(num));
  17.         num += 1;
  18.     }
  19.     return arr;
  20. }
  21.  
  22. function getOnes(num) {
  23.     const binStr = num.toString(2);
  24.     let count = 0;
  25.     for (let i = 0; i < binStr.length; i++) {
  26.         if (binStr[i] == 1) count += 1;
  27.     }
  28.     return count;
  29. }
Advertisement
Add Comment
Please, Sign In to add comment