10, the number of 1 in binary

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

  Idea : first determine whether it is 0, if it is not 0, there is at least one 1, set a variable to count the number of 1, then subtract 1 from the binary number, and do an AND operation with the original number after the subtraction, so that this 1 will be disappear. Repeat this, incrementing this variable by 1 each time, until all 1s disappear.
  Example: 1100. Judgment is not 0, so the variable is +1, and then subtracted by 1, it becomes 1011, and then with 1100 to get 1000, the variable is +1 again, and then 1000 is subtracted by 1, to get 0111, and then with 1000 to do the AND operation, get 0, end. Get 2 1s.

  Test cases :
  1. Positive numbers (including boundary values ​​1, 0x7FFFFFFF).
  2. Negative numbers (including boundary values ​​0x80000000, 0xFFFFFFFF).
  3.0

#include<iostream>
using namespace std;

int NumberOf1(int n)
{
    int count = 0;

    while (n)
    {
        ++count;
        n = (n - 1) & n;
    }

    return count;
}

//测试
void test1()
{
    int n1 = 1;
    int n2 = 0x7FFFFFFF;
    int count1 = NumberOf1(n1);
    int count2 = NumberOf1(n2);
    cout << count1 << endl;
    cout << count2 << endl;
}

void test2()
{
    int n1 = 0x80000000;
    int n2 = 0xFFFFFFFF; //取反加1
    int count3 = NumberOf1(n1);
    int count4 = NumberOf1(n2);
    cout << count3 << endl;
    cout << count4 << endl;
}

void test3()
{
    int n = 0;
    cout << NumberOf1(n) << endl;
}

int main()
{
    test1();
    test2();
    test3();

    return 0;
}

 

 Related topics :
  
  Topic : Use a statement to determine whether an integer is a power of 2.

  Idea : If a positive number is an integer power of 2, then only one of its binary representations is 1, and all other bits are 0. According to the previous analysis, after subtracting 1 from this integer and then doing an AND operation with itself, the only 1 in this integer will become 0.


  Question : Input two integers m and n, and calculate how many bits in the binary representation of m need to be changed to get n. For example, the binary representation of 10 is 1010, and the binary representation of 13 is 1101. You need to change 3 bits in 1010 to get 1101.

  Idea : The first step is to find the XOR of these two numbers, and the different bits will be 1, and the second step is to count the number of 1s.


  By analogy :
  subtract 1 from an integer and then perform a bitwise AND operation with the original integer. The result is equivalent to changing the rightmost 1 in the binary representation of the integer to 0. Many binary problems can be solved with this idea.

Guess you like

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