LeetCode: Counting Bits Solution

Convert to binary with toString() method

Approach

Convert number to binary string using .toString(2)

Count the 1s

Implementation

1var countBits = function (n) {
2 return Array.from(
3 { length: n + 1 },
4 (_, i) => i.toString(2).replace(/0/g, "").length
5 )
6}

References

Original problem

String.prototype.toString()

Comments

Loading comments...

Tags

leetcode

string

bit manipulation

Next Post

LeetCode: Longest Palindrome

Trim odds

Previous Post

LeetCode: Is Subsequence

The author is not smart enough to come up with the DP solution in the first place

HoningJS

Search Posts