Bit Counter

Bit Counter

Medium C Operators 41 views
Explanation Complexity

Problem Statement

Count the number of 1 bits in an integer using bitwise operators. Use the & operator in a loop and right shift it.

Input Format

An integer number.

Output Format

An integer representing the count of 1 bits in the binary representation.

Example

13
3

Constraints

• Integer ≥ 0

Concept Explanation

The task is to count how many bits are set to 1 using bitwise operations.

Step-by-Step Explanation

1.Initialize a variable count = 0.

2.While the number is greater than 0:

3.Use bitwise AND with 1 (n & 1):

• If the result is 1, increment count.

4.Right shift the number by 1 (n >> 1).

5.Repeat until the number becomes 0.

6.count contains the total number of 1 bits.

Concept Explanation

The task is to count how many bits are set to 1 using bitwise operations.

Step-by-Step Explanation

1.Initialize a variable count = 0.

2.While the number is greater than 0:

3.Use bitwise AND with 1 (n & 1):

• If the result is 1, increment count.

4.Right shift the number by 1 (n >> 1).

5.Repeat until the number becomes 0.

6.count contains the total number of 1 bits.

Input / Output Format

Input Format
An integer number.
Output Format
An integer representing the count of 1 bits in the binary representation.
Constraints
• Integer ≥ 0

Examples

Input:
13
Output:
3

Example Solution (Public)

C
#include <stdio.h>

int main() {
    unsigned int n;
    int count = 0;

    printf("Enter an integer: ");
    scanf("%u", &n);

    while (n > 0) {
        if (n & 1) {   // check least significant bit
            count++;
        }
        n = n >> 1;    // right shift by 1 bit
    }

    printf("Number of 1 bits = %dn", count);

    return 0;
}

Official Solution Code

#include <stdio.h>

int main() {
    unsigned int n;
    int count = 0;

    printf("Enter an integer: ");
    scanf("%u", &n);

    while (n > 0) {
        if (n & 1) {   // check least significant bit
            count++;
        }
        n = n >> 1;    // right shift by 1 bit
    }

    printf("Number of 1 bits = %dn", count);

    return 0;
}
Please login to submit solutions.
Editor
Output

                                        
Please login to submit solutions.