Find the number of 1 in a binary binary:
General Method :
#include <stdio.h>
#include <stdlib.h>
int count_one_bits (unsigned int value)
{
int count = 0;
for (int i = 0; i <; i++)
{
if (value & 1 = = 1) (%2 equivalent to &1)
{
count++;
}
value = value >> 1; (move right one equivalent to 2)
}
return count;
}
int Main ()
{
unsigned int value= 0;
scanf ( "%d" , &value);
int ret = count_one_bits (value);
printf ( "%d\n" , ret);
System ( "pause" );
return 0;
}
650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>
650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/7D/8F/wKioL1bq0_zwLZmZAAB6YBz1nPk838.png "title=" Untitled. png "alt=" Wkiol1bq0_zwlzmzaab6ybz1npk838.png "/>
Optimization:
#include <stdio.h>
#include <stdlib.h>
int count_one_bits (unsigned int value)
{
int count = 0;
while (value )//value enters a loop if nonzero
{
count++; Because value is not 0, there is at least one 1 in the binary
value = value & (value -1); N and n& (n-1) binary is always a difference of 1
}
return count;
}
int Main ()
{
unsigned int value= 0;
scanf ( "%d", &value);
int ret = count_one_bits (value);
printf ( "%d\n", ret);
System ( "pause");
return 0;
}
To ask a number of books is not 2 of the n-th square:
#include <stdio.h>
int main ()
{
int num=0;
scanf ("%d", &num);
if (value & (value -1)) ==0);
printf ("yes\n");
Else
printf ("no\n");
return 0;
}
This article is from the "11132019" blog, please be sure to keep this source http://11142019.blog.51cto.com/11132019/1752371
Find the number of 1 in a binary binary (optimized). Determine if a number is 2 of the n-th square