Concise, Readable JS Solution

  • 0

    I made a function to give me the bitCount for an individual number and logged out every number in order until I was able to see the pattern of groups of 4 starting from a number, incrementing 1, repeating, and incrementing 1. Then I noticed that the same pattern occuring over the entire series of numbers occurs for the first of every 4 numbers. Using this knowledge, I decided to keep track of an index that increments ever 4 numbers and gives me that value from the numbers I've already produced in order to determine what number the next group of 4 should start with. Here's what I ended up with. Next steps would be to cache groups of 4 for each starting number so that when I get to a starting number I've been to before, I can just push a copy of them into my array and remove any excess.

    const countBits = (num) => {
        const bitCounts = [0]
        let histIdx = 0, val = 0
        for (let i = 1; i <= num; ++i) {
            if (i % 4 === 0) {
                val = bitCounts[histIdx]
            if (i % 2 === 1) ++val
        return bitCounts

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.