01. Number of 1 Bits
The problem can be found at the following link: Question Link
My approaches
Since this question is relatively simple and can be solved in multiple ways, I would like to present two commonly used approaches.
Approach 1:
The first approach involves iterating through the bits of the binary representation of the number and counting the set bits. Here how it works:
We repeatedly
right-shift
the number by1 bit
and add therightmost
bit to the counter variablecnt
if it is1
counter increased . If the bit is0
, the counter remains unchanged.
Example
Time and Auxiliary Space Complexity
Time Complexity :
O(log(n))
, as we iterate through all the bits ofn
, which totals tolog(n
).Auxiliary Space Complexity :
constant
as it does not depend on variables
Code (C++)
Approach 2:
The second approach utilizes the standard library function __builtin_popcount(n)
in C++ to count the number of set bits. This approach involves a concise one-liner code using the built-in function.
Code (C++):
Time and Auxiliary Space Complexity
Time Complexity :
O(k)
, where k is the number of bits.Auxiliary Space Complexity :
constant
as it does not depend on variables
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated