V
Vish
Hi All
I have written a program to count the maximum contiguous set bits in an
integer .
Like if my binary representation of integer is :
1100111 : then output should be 3.
111000111110000101010111111 : then output should be 6.
I am including the snippet below.
How can I optimize this code and also is there a one liner to
implement the same.
(Like for power of 2 we have got (number & (number -1))).
Here is the program:
int main()
{
int count=0,n,i,temp=0;
printf("Enter the number \n");
/*Numer is in decimal for calculation we have to use binary
representation for calculation*/
scanf("%d",&n);
for (i=0;i<(8*sizeof(int));i++)
{
if((n&1)==1)
count++;
else
{
if (temp<count)
temp=count;
count=0;
}
n= n>>1;
}
if (temp==0)
printf("count of contiguous bits= %d\n",count);
else
printf("count of contiguous bits = %d\n",temp);
return 0;
}
I have written a program to count the maximum contiguous set bits in an
integer .
Like if my binary representation of integer is :
1100111 : then output should be 3.
111000111110000101010111111 : then output should be 6.
I am including the snippet below.
How can I optimize this code and also is there a one liner to
implement the same.
(Like for power of 2 we have got (number & (number -1))).
Here is the program:
int main()
{
int count=0,n,i,temp=0;
printf("Enter the number \n");
/*Numer is in decimal for calculation we have to use binary
representation for calculation*/
scanf("%d",&n);
for (i=0;i<(8*sizeof(int));i++)
{
if((n&1)==1)
count++;
else
{
if (temp<count)
temp=count;
count=0;
}
n= n>>1;
}
if (temp==0)
printf("count of contiguous bits= %d\n",count);
else
printf("count of contiguous bits = %d\n",temp);
return 0;
}