C Program to find the number of Set Bits(1's) in a Binary Number - Bit Manipulation

    


// Program by Akash Tripathi (@proakash256) 
 
// Example : Let a = 10110
// As we can see, there are
// 3 set bits or 1's in the number

#include <stdio.h>
void binary(int n)
{
    // Prints the Binary Representation
    // of a Decimal Number upto 11 bits.
    for(int i = 10i >= 0i = i - 1)
    {
        printf("%d" , ((n >> i) & 1));
    }
    printf("\n");
    return;
}
int main()
{
    int n;
    printf("Enter the Number : ");
    scanf("%d", &n);
    printf("Binary Representation of %d is : "n);
    binary(n);
    int temp = n , c = 0;
    // To find 1's,
    // we have two methods.

    // Method 1:
    // Find (n & 1)
    // if((n & 1) == 1) then counter++
    // if((n & 1) == 0) then continue
    // n >> 1
    // Repeat till n == 0
    // Time Complexity = (log n)

    while(temp != 0)
    {
        if((temp & 1) == 1)
            c = c + 1;
       temp = temp >> 1;
    }
    printf("\nBy First Method :\n");
    printf("\nThere are %d Set Bits
            n %d.\n\n" , c , n);
    temp = n;
    c = 0;

    // Method 2:
    // Find n & (n - 1)
    // It removes the last significant bit
    // keep increasing the counter by 1
    // till it is equal to 0

    while(temp != 0)
    {
        temp = (temp & (temp - 1));
        c = c + 1;
    }
    printf("\nBy Second Method :\n");
    printf("\nThere are %d Set Bits
            in %d.\n\n" , c , n);
    return 0;
}

 

Comments