* Returns the number of 1 in a binary representation of a number. *
#include <stdio.h>int main () { unsigned int i; &NBSP;SCANF ("%d", &i); printf ("%d binary expression has %d 1", i,count_one_bits (i)); return 0;} Int count_one_bits (unsigned int m) { int n,count; // return 1 number of digits n = m; count = 0; while (n % 2 == 0) n = n / 2; while (n % 2 == 1) { count++; do { if (n != 0) n = n / 2; else break; } while (n % 2 == 0); } return count;}
This is the most easy way to think of, and constantly in addition to 2 modulo 2 to take the remainder, the following gives another method (omit part of the statement)
... i = 32;while (i--) {if (num & 1 = = 1) count++; num = num>>1;}
This method is shifted to the right, so that the lowest bits & 1 are judged, and a more efficient method
int count_one_bit (int num) {int count = 0; while (num) {count++; As long as a number is not 0, then there is at least one 1 num in the binary expression = num & (num-1);//The statement is not executed once, in fact, the lowest bit of the number of a 1 to 0} return count;
This article is from the "Knock Code good Sleep zzz" blog, please be sure to keep this source http://2627lounuo.blog.51cto.com/10696599/1703820
How many different solutions to 1 in a number bits