The number of binary 1: 3 title

Subject description:

  Please design a function, a number of inputs, outputs the number 1 indicates the number of two, Ltd.   

   Example: 9 is represented as two system 1001 has two 1

Problem-solving ideas:

  This is the main question test sites using flexible binary conversion and bit operations. I have listed three ways to achieve it :

  Method a : Method 1 elimination (Principle: N - 1 may be N 1 of the least significant bit is 0, the characteristics of the back 1 is the least significant bit of 0, N & (N - 1) can be eliminated to a least significant bit, the last time until elimination of a 1, the result is 0)

  Method two : 32 cycles, using 1 bit arithmetic and bitwise comparison Comparison

  Method three : when binary conversion, to accumulate the remainder is 1  

 @ Method a: Method 1 elimination 
    public  static    int F ( int n-) {
         int COUNT = 0 ;
         the while (! = N-0 ) {// when the result is zero, indicating that no one, not erased 
            n- = & n-(N- 1);       // erase method 1 core 
            cOUNT ++;          // every time an erase count plus 1 
        }
         return cOUNT; 
    }
 @ Method 2: Using 32 cycles, bit-wise comparison 
    public  static  int F2 ( int n-) {
         int COUNT = 0 ;
         for ( int I = 0; I <32; I ++ ) {
             IF (((n->> I) & 1) == 1) { // right i bit, and let a bit with the lowest operation. 
                ++ COUNT ; 
            } 
        } 
        return COUNT; 
    }
@ Method three: when the binary switch, the remainder of the statistical 1 
    public  static  int F3 ( int n-) {
         int COUNT = 0 ;
         int Shang = n-; 
         int Yu;
         the while (Shang = 0!) {   // decimal binary switch core 
            Yu Shang% = 2;         // to find remainder 
            Shang Shang = / 2;     // then quotient 
            IF (Yu ==. 1 ) {         
                COUNT ++;     // for the remainder of a statistical 
            } 
        } 
        return COUNT; 
    }

 

Guess you like

Origin www.cnblogs.com/songchengyu/p/12590308.html