"Sword Pointing Offer" Java implementation - the number of 1 in binary

topic

Input an integer and output the number of 1's in the binary representation of the number. Negative numbers are represented in complement.

ideas

The idea of ​​​​this question is very clever. If an integer is not 0, then at least one of the binary digits of the integer is 1. If we subtract 1 from this integer, the 1 that was originally on the rightmost side of the integer will become 0, and all 0s that were originally after the 1 will become 1s (if there are 0s after the rightmost 1). All remaining bits will not be affected. For example, 1110, minus 1 equals 1101; perform an AND operation to get 1100.

code

public class Solution {
    public int NumberOf1(int n) {
        int count=0;
        while(n!=0){
            n = n&n-1;
            count++;
        }
       return count;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325640413&siteId=291194637