Count Set Bits (1s) in Binary
C++
Hard
4 views
Problem Description
Count how many 1s are in binary representation of number.
Real Life: Used in computer architecture, compression.
Step-by-Step Logic:
1. Check last bit using & 1
2. If 1, increment counter
3. Right shift number by 1
4. Repeat until number becomes 0
5. Return count
Official Solution
void operator_q11_count_set_bits() {
int num = 29; // Binary: 11101
int count = 0;
int temp = num;
while(temp > 0) {
if(temp & 1) { // Check last bit
count++;
}
temp = temp >> 1; // Right shift
}
cout << "Number: " << num << endl;
cout << "Set bits (1s) in binary: " << count << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!