The sword refers to Offer-question 15 (Java Edition): the number of 1 in binary

Reference from: "Sword Pointing Offer - Famous Enterprise Interviewer Talking About Typical Programming Questions"

Question : Number of 1s in Binary
Please implement a function that inputs an integer and outputs the number of 1s in the binary representation of the number. For example: Representing 9 in binary is 1001, and 2 bits are 1. So if you enter 9, the function outputs 2.

Main idea : Subtracting 1 from an integer turns the rightmost 1 into 0. If there are 0s to its right, all 0s to its right become 1s, and all bits to its left remain unchanged. Therefore, performing a bitwise AND operation on an integer and the result of subtracting 1 from it is equivalent to changing its rightmost 1 to 0, and so on until the number becomes 0, then the number of operations is the number of 1s.
For example: 1100; 1100-1 =1011; 1100&1011 =1000

Extension : This method can also be used to determine whether an integer is a power of 2, that is, whether the integer has only one 1 in its binary representation.

Key Point : Bit Operations

Time complexity : O(n), where n is the number of 1s in the desired number

public class NumberOfOneInBinary
{
    public static void main(String[] args)
    {
        int n = 9;
        System.out.println(numberOfOne(n)); //2
        int n1 = 0x7FFFFFFF;
        System.out.println(numberOfOne(n1)); //31
    }

    private static int numberOfOne(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=325891036&siteId=291194637