881893. Set bits in N
Basic
Set bits in N
Summary
Given a positive integer N, write an algorithm to count the number of set bits (bits that are equal to 1) in the binary representation of N. This problem involves understanding the concept of bitwise operations and manipulation.
Detailed Explanation
To solve this problem, we can use a simple bitwise operation. The idea is to use the bitwise AND operator (&) to find the set bits in the binary representation of N.
Here's a step-by-step breakdown of the solution:
- Initialize a variable
set_bitsto 0. - Loop through each bit in the binary representation of
N, starting from the least significant bit (rightmost) to the most significant bit (leftmost). - For each bit, use the bitwise AND operator (
&) with the current bit and the number 1. This will give us a result that is either 0 (if the bit is not set) or 1 (if the bit is set). - If the result is non-zero, increment
set_bitsby 1. - After looping through all bits, return the value of
set_bits.
Here's an ASCII art diagram to illustrate this process:
N: 11001010
^ ^
| |
v v
1 & 1 = 1 // set bit
0 & 1 = 0 // not a set bit
...
0 & 1 = 0 // not a set bit
Time complexity: O(log N) (where N is the input integer)
Space complexity: O(1)
Optimized Solutions
Java
public int countSetBits(int n) {
int set_bits = 0;
while (n > 0) {
if ((n & 1) == 1) {
set_bits++;
}
n >>= 1;
}
return set_bits;
}