01. Number of 1 Bits
Last updated
Was this helpful?
Last updated
Was this helpful?
The problem can be found at the following link:
Since this question is relatively simple and can be solved in multiple ways, I would like to present two commonly used approaches.
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 by 1 bit
and add the rightmost
bit to the counter variable cnt
if it is 1
counter increased . If the bit is 0
, the counter remains unchanged.
Time Complexity : O(log(n))
, as we iterate through all the bits of n
, which totals to log(n
).
Auxiliary Space Complexity : constant
as it does not depend on variables
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.
Time Complexity : O(k)
, where k is the number of bits.
Auxiliary Space Complexity : constant
as it does not depend on variables
For discussions, questions, or doubts related to this solution, please visit our . 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 repository.