Friday, September 1st
Counting Bits
Given a number n, return an array of length n+1 such that for each index, the array gives the number of 1's in the index's binary representation
The observation is that for a given number x, if x is even, then the number of ones is the same as x/2, because you're just swapping between which of 2 bits are set to 1.
Similarly, if x is odd, then the number of bits is equal to the floor(x/2) + 1, because like before, you're just switching with even bit is on, plus adding an extra bit for the remainder
To code, we first start out with the base case 0
Then we iterate through the remaining input values n. If the number is even, we add the number of ones in half the value, otherwise we add the number of ones in half the value, plus an extra
Finally return the result
A little testy, but lots of different interesting solutions for the problem. A tougher easy than most
Full code below
}
Comments
Post a Comment