//15 //00001111>>1 //00000111 int count_bit(unsigned int value) { int one = 0; while(value) { if(value%2 == 1) one++; value = value >> 1; } return one; }
//x&1; n += x &1; x>>=1; //1111 & 0001 = 0001 n=1 //0111 & 0001 = 0001 2 //0011 & 0001 = 0001 3 //0001 & 0001 = 0001 4 int count_bit1(unsigned int x) { int n=0; do { n += x &1; x>>=1; } while (x!=0); return (n); }
//x&(x-1) //1111 & 1110 = 1110 //1110 & 1101 = 1100 //1100 & 1011 = 1000 //1000 & 0111 = 0000 int count_bit2(unsigned int value) { int count = 0; while(value) { count++; value = value & (value-1); } return count; }
时间: 2024-10-06 11:08:14