Calculating a number of number of number 1, 0

 

1. The number of seeking a binary number 1 int

(1) 1, {right positive and negative numbers are (is negative calculate the number of 1s complement)]

int a;
CIN >> A;
 int COUNT = 0 ; 
int n-= the sizeof ( int ) * . 8 ; // bits for ( int I = 0 ; I <n-; I ++ ) { IF (& A . 1 =! 0 ) {// Analyzing whether the least significant bit is 1 ++ COUNT; } A >> = 1 ; // right one }
cout
<<count<<endl;

 

(2) the equivalent of the right divided by 2

  Analyzing the lowest available bit modulo 2; available right by 2 [This method is only suitable for a positive number, unsigned number]

int a;
cin>>a;
int count = 0;

while(a>0) {
   count += (a%2);
   a /= 2;
}

cout<<count<<endl;

 

(3) [with the positive, negative, which can be smaller than the number] 1

int a;
cin>>a;
int count = 0;
while(a!=0) {
    ++count;
    a &= (a-1);
}
cout<<count<<endl;

 

2. The required number 0

(1) 1, right

  If 1 and 0, then the count is incremented by 1; and 1 is 1, it is determined that a

 

(2) the total number of bits minus 1

 

Guess you like

Origin www.cnblogs.com/taoXiang/p/12649829.html