Judge the number of 1 in 32-bit integer binary

Source: Internet
Author: User
Tags findone

I was asked this question during the interview: it is not difficult to judge the number of 1 in a 32-bit unsigned integer binary. However, it requires optimization at different layers. Now let's sort it out:

1. Basic Ideas:

# Include <iostream>


Using namespace STD;


Int findone (unsigned int N ){

For (INT I = 0; n> 0; n> = 1)

I + = (N & 1 );

Return I;

}


Int main (){

Int N;

Cin> N;

Cout <findone (n) <Endl;

Return 0;

}

2. Optimization:

The time complexity is T (m) = m, depending on the number of digits of the binary number M. What should I do if I want to find it in a shorter time? If the findone function is repeatedly called (thousands of calls), how should we optimize it?

In fact, it is the idea of changing the space time: You can pre-create a table and store it from 0 ~ 2 ^ 32 indicates the number of 1 in each number. You can check the table when necessary. But this obviously takes a lot of space (at least 2 ^ 32/(256/32) = 512 MB, haha, it is the general memory size ). Therefore, optimization is required: store the number of 1 in each number from 0 to, and then perform segmented query. For example, the 32-digit table is divided into 4 segments, each segment contains one byte, so there is a 256-bit table for query:
Char tone [256] = "\ 0 \ 1 \ 1 \ 2 \ 1 \ 2 ...... "; // Unspecified



Int findone (unsigned int N ){

For (INT I = 0; n> 0; n> = 8)

I + = tone [N & 255];

Return I;

}

3. It is said that intel has an assembly command (or several) to complete this work, but it does not know what it is and how it should be done.

4. You can see the same things in youdao MS:
Int func (unsigned int N ){

Int COUNT = 0;

While (n> 0 ){

N & = (n-1 );

Count ++;

}

Return count;

}

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.