1. Find the number of int data stored in memory 1
Enter an int data to calculate the number of 1 when the int data is stored in memory.
We can easily think of the following methods:
#include <iostream>using namespace Std;int main () {int n,cnt=0;cin>>n;while (n) {if (n%2==1) CNT++;N=N/2;} Cout<<cnt<<endl;return 0;}
Entering a negative number when testing the code cannot be concluded, and the following method will solve the problem.
#include <iostream>using namespace Std;int getcount (int n) {int m=0;while (n) {n&= (n-1); m++;} return m;} int main () {int a;cin>>a; Cout<<getcount (a) <<endl;}
If we subtract this integer by 1, then the 1 at the far right of the integer will become 0, and all 0 after 1 will become 1. All remaining bits will not be affected. For example: A binary number 1100, the third digit from the right number is the one on the rightmost 1. After subtracting 1, the third bit becomes 0, the two bit 0 behind it becomes 1, and the preceding 1 remains the same, so the result is 1011.
We found that the result of minus 1 was to reverse all the bits starting from the rightmost 1. This time if we do the original integer and minus 1 after the result of the operation, from the original integer to the right of the first 1 that the beginning of all the bits will become 0. such as 1100&1011=1000. That is, subtracting an integer by 1, and then doing and arithmetic with the original integer will change the rightmost 1 of the integer to 0. Then the number of binary numbers of an integer is 1, so how many times such operations can be performed.
For example, in the above-10, the 32-bit machine is represented as 1111111111111111 1111111111110110, so the number of 1 is 30.
The number of int data stored in memory 1