The number of int data stored in memory 1

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.