C language finds the number of 1s in an integer stored in binary in memory

Table of contents

1. Topic requirements

2. Problem-solving ideas

(1) Method 1

1). Analysis

2). Code Demo

(2), Method 2

1). Analysis

2). Code demonstration


1. Topic requirements

Find the number of 1's in binary stored in memory for an integer.

We can know from the title that the binary digits of an integer in memory are the complement of the integer, so we are looking for the number of 1s in the complement of the integer.

2. Problem-solving ideas

(1) Method 1

1). Analysis

Thinking in another way, if we are looking for the number of 1s in an integer, what we think at the beginning is to separate the digits of the integer, and then use the loop method to make judgments and count them.

As for the method of separating the digits of an integer, we can use the method of first %10 and then /10, the former takes out the lowest digit, the latter removes the lowest digit, and loops, we can get an integer All digits.

For example:

123 %10 = 3 

123 / 10 =  12

12 % 10 =  2

12 / 10 = 1

1 % 10 = 1

1 / 10 = 0

When the final answer is 0, the loop has ended.

Therefore, we can use this method to solve the separation of each digit of the binary number

For example:

 1111 - 15 in binary

15 % 2 = 1

15 / 2 =  7

111 - 7 in binary

7 % 2 = 1

7 / 2 = 3

11 - 3 binary

………………………………

and so on  

But this method will have problems when facing negative numbers, so a new method has been created, using >> and &.

& has the function of judging whether it is 1. When used with >>, it can judge whether each digit is 1

The function details of & are at http://t.csdn.cn/mqp1G

So with the following code demonstration

2). Code Demo

int main()
{
  int a = 0:
  scanf("%d"&a);
  int i = 0;
  int count = 0;
  for (i = 0;i < 32; i++)
  {
    if ((a >> i) & 1) == 1)//进行移位判断,利用了&的性质
     { 
       count++;//等于1的进行统计,不等于1的直接进入循环
     }
   }
  printf("%d\n",count);
  return 0;
}

(2), Method 2

1). Analysis

For example:

int n = 13;

110 1 - n's complement

1100 - n-1's complement

1100 - the result of n & (n-1), make this n & (n-1) the new n

1 1 00 - n's complement

1011 - n-1's complement

1000 - the result of n&(n-1), make this n & (n-1) the new n

1 000 - n's complement

…………………………

Through the above, we know that compared with the old n, the number of 1 in the binary digits is gradually decreasing, and it decreases from right to left. Therefore, we can get a rule, n = n & (n-1) 1 in ever decreasing binary digits.

So, we produced the following code.

2). Code demonstration

int main()
{ int n = 0:
  scanf("%d",&n);
  int count = 0;
  while (n)
  {
    n =n & (n - 1);
    count++;
  }
  printf("%d\n",count);
  return 0;
 }

Guess you like

Origin blog.csdn.net/2301_76445610/article/details/132140044