Once's in Binary Representation of a Number
Let’s explore how to count the number of 1
s (also known as ones) in the binary representation of a number. We'll take the number n = 7
as an example.
Initialization: Start with a count of
0
.Binary Representation: The binary representation of
7
is111
, which contains3
ones. Thus, we increment our count to1
.Bit Manipulation: Now, we perform a bitwise operation to remove the rightmost
1
:n = 7
(binary111
)- When we apply the operation
n & (n - 1)
, we get:7 - 1 = 6
(binary110
)7 & 6 = 6
(binary110
)
After this operation, the count of
1
s is now2
(for the binary110
).Repeat: We continue this process:
- Now
n = 6
(binary110
)6 - 1 = 5
(binary101
)6 & 5 = 4
(binary100
)
The count increases to
3
.- Now
Final Steps: We continue until
n
becomes0
:n = 5
(binary101
)5 - 1 = 4
(binary100
)5 & 4 = 0
(binary000
)
At this point,
n
is0
, and the final count of ones is3
.
Code Implementation
Here is the code that implements this process:
Explanation of the Code
- Function Definition: The function
count_ones
takes an integern
as input. - Count Variable: We initialize a counter (
count
) to0
. - Loop Until Zero: We use a
while
loop that continues untiln
becomes0
.- In each iteration, we increment the count and update
n
by clearing the rightmost1
usingn & (n - 1)
.
- In each iteration, we increment the count and update
- Return Count: Once the loop ends, the function returns the total count of ones.
Conclusion
This method is efficient for counting the number of 1
s in the binary representation of a number using bitwise operations. You can test the code by inputting any integer, and it will display the number of ones in its binary form.
Comments
Post a Comment