AD1

Saturday, 17 June 2017

Count Set bits in an array of integers

assume you have an array of 5 integers and you want to count the numbers of set bits in all array elements , write a function to do that

Solution
#include <stdio.h>
#include <stdlib.h>
#define size 5
int count_set_bits(int *array)
{
int count=0;
for(int i=0;i<size;i++)
{
for(int j=0;j<32;j++)
{
if(array[i]&(1<<j))
{
count++;
}
}
}
return count;
}
int main(int argc, char** argv) {
int data[size]={1,2,3,4,5};
printf("Number of set bits in this array = %d bits \n",count_set_bits(data));
return (EXIT_SUCCESS);
}
view raw setbits.c hosted with ❤ by GitHub


No comments:

Post a Comment