Count Set Bits (1s) in Binary

Count Set Bits (1s) in Binary

Hard C++ Operators 43 views
Explanation Complexity

Problem Statement

Count how many 1s are in binary representation of number.
Real Life: Used in computer architecture, compression.

Input Format

An integer N.

Output Format

Count of 1s in the binary representation of N.

Example

13
3
Explanation: 13 → binary 1101 → three 1s)

Constraints

• N ≥ 0

• Use bitwise operations

Concept Explanation

The number of 1 bits in binary shows how many bits are set.
This is used in computer architecture and data compression.

Step-by-Step Explanation

1.Take input number N.

2.Initialize count = 0.

3. While N > 0:

• Check last bit using N & 1.

• If it is 1, increment count.

• Right shift N by 1.

4.When N becomes 0, stop.

5.Print count

Concept Explanation

The number of 1 bits in binary shows how many bits are set.
This is used in computer architecture and data compression.

Step-by-Step Explanation

1.Take input number N.

2.Initialize count = 0.

3. While N > 0:

• Check last bit using N & 1.

• If it is 1, increment count.

• Right shift N by 1.

4.When N becomes 0, stop.

5.Print count

Input / Output Format

Input Format
An integer N.
Output Format
Count of 1s in the binary representation of N.
Constraints
• N ≥ 0

• Use bitwise operations

Examples

Input:
13
Output:
3 Explanation: 13 → binary 1101 → three 1s)

Example Solution (Public)

C++
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;
}

Official Solution Code

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;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.