Bitwise operations--counting the number of 1 in a binary sequence of one number

Source: Internet
Author: User

Give a decimal number to find out the number of 1 in the binary sequence of the numbers. For example, a 15 binary sequence is

00000000 00000000 00000000 00001111 1 The number is 4.

Here are a few different ways to solve the problem:

Method One:

int count_one (int num) {int count = 0;while (num) {if (num% 2 = = 1) {count++;} num = NUM/2;} return count;}


Because this method uses the modulo to divide the operation, therefore this method can only handle positive numbers, for negative numbers, is not possible.

Method Two:

int count_one (int num) {int count = 0;int i = 0;for (i = 0;i < 32;i++) {if (num >> i) & 1 = = 1) {count++;}} return count;}


This method can calculate both positive and negative numbers, which is a little bit less efficient. Like some decimal numbers.

The number of bits converted to binary is much less than 32, but we have to shift the judgment 32 again.

Method Three:

</pre><pre name= "code" class= "CPP" >int count_one (int num) {int count = 0;while (num) {count++;num = num & (n UM-1);} return count;}



This solution uses a number and a number that is entering primary one than it is logically related, and a 1 less in the binary.

Example: 7 0111

0110 logic with afterwards the result is: 0110

A number if it is 2 of the N-square, then POW (2,n) & (POW (2,n)-1) = = 0; Use this to determine whether a number is

is 2 of the n-th square.

Method Four:

First look at the picture:


int count_ones (int num) {int m_2 = 0x55555555;int M_4 = 0x33333333;int M_8 = 0x0f0f0f0f;int M_16 = 0x00ff00ff;int B = (m_2& Amp;num) + ((num >> 1) &m_2), int c = (m_4&b) + ((b >> 2) &m_4), int d = (m_8&c) + ((c >> 4) &m_8); int g = (m_16&d) + ((d >> 8) &m_16); return g;}


Finally this method, is according to 4 byte int processing, if you do not understand, private messages me. Mailbox:

[Email protected]

Bitwise operations--counting the number of 1 in a binary sequence of one number

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.