2.Counting Bits
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
Solution I : (Using STL)
Solution II:(Brian Kernighan’s Algorithm)
Time Complexity: O(n log n)
Solution III: (Using property of even odd no and division)
Algorithm: If i is even then it will have the same number of set bits as i / 2 because to get the number i we just shift the LSB in i / 2 by one. While shifting, the number of set bits in i/2 does not change. If i is odd then dividing the number means doing 1 right shift and here 1 set bit will be lost. So the number i/2 will have 1 set bit less than the original number.
Time Complexity: O(n) , Space Complexity:O(n)
Last updated