Given an integer n, the task is to count the numbers having only 1 set bit in the range [0, n].
Input: n = 7
000, 001, 010, 011, 100, 101, 110 and 111 are the binary representation of all the numbers upto 7.
And there are only 3 numbers ( 001, 010 and 100 ) having only 1 set bit.
Input: n = 3
Approach: If k bits are required to represent n then there are k numbers possible as 1 can be positioned at k different positions each time.
Below is the implementation of the above approach
Time Complexity: O(log n)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
In case you wish to attend live classes with industry experts, please refer Geeks Classes Live