The number of binary 1 - prove safety offer

An integer that indicates the number of the output of the binary number 1 in. Wherein a negative number indicates a complement.

1 and wanted to make the beginning of the operational position to the right and then the test fails because the negative bit right shift by 1 bit to fill, resulting in judgment can not be terminated. So another way

1 and still do the operation, but one left, until a left turn into 0 so far, if the bit of the result is not 0, the results ➕1;

public class Solution {
    public int NumberOf1(int n) {
        int base = 1;
        int sum=0;
        while(base != 0){
            if((n&base) != 0){
                sum ++;
            }
            base=base << 1;
        }
        return sum;
    }
}

Recording an online method:

The n minus 1, and then ANDed with the original n, the calculation result is not 0 indicates a bit is 1, the cycle

Example with: n is the binary representation of 1110 minus 1101 and 1110 and 1 to 1101 with the operation result of one operation 1100 may be described to have a 1, this continues to find all 1;

public  class Solution {
     public  int NumberOf1 ( int n) {
         int COUNT = 0 ; 
// long as n is not 0, it means there is a bit. 1
the while (n = 0! ) { count ++; n = n&(n-1); } return count; } }

 

Guess you like

Origin www.cnblogs.com/nlw-blog/p/12417794.html