Write a function to return the number of 1 in a parameter binary
For example: 15 0000 1111 4 x 1
Program prototypes:
int count_one_bits (unsigned int value)
{
Returns the number of digits in 1
}
Method one: (modulo) disadvantage; The case that the decimal is negative is not considered, example 1 bit=0#include<stdio.h> #include <stdlib.h>int main () {int count = 0;int num =-1 ; scanf ("%d", &num), while (num) {if (num% 2 = = 1) {count++;} num = NUM/2;} printf ("count=%d\n", count); System ("pause"); return 0;}
Method Two: (Bitwise AND and SHIFT)
int main () {int count = 0;int num = 15;int i = 32;while (i) {if (num & 1 = = 1) {count++;} num = Num/2;num = num >> 1;i-= 1;} printf ("count=%d\n", count); System ("pause"); return 0;}
Method Three: (x=x& (x-1))
#include <stdio.h> int main () {int count = 0;int num = 0;scanf ("%d", &num), while (num) {count++;num = num & (num -1);//Number of 1}printf ("Count =%d\n", count); return 0;}
Report:
(1) num=x& (x-1) to determine whether it is 2^n, then num= (num-1) &num is 00
(2) int count_one_bits (unsigned int value), positive number does not need to consider complement, negative number need to consider complement,
unsigned int value is clever in that negative numbers can also be used
This article is from the "Little Gray Ash" blog, please make sure to keep this source http://10742910.blog.51cto.com/10732910/1719787
Number of 1 in a binary number