Algorithm-to find the number of 1 in a binary number

Source: Internet
Author: User

Common:

I am always used to call the common law, because I really can not find a proper name to describe it, in fact, is the simplest way, a little program based on the people are able to think, that is the SHIFT + count, very simple, not much to say, directly on the code, this method of operation of the number of input n is the highest bit 1 of the

intBitcount (unsignedintN) {unsignedintc =0;//counter     while(N >0)    {        if(N &1) ==1)//the current bit is 1++c;//counter plus 1N >>=1;//Shift    }    returnC;}

A more streamlined version is as follows

int int N) {    int c =0//  counter     for (c =0; n; n >>=1//  cyclic shift        c + = n &1// if the current bit is 1, the counter plus 1    return C;}

Fast method

This method is faster and has no relation to the size of the input n and is only related to the number of 1 in N. If the binary representation of N has K 1, then this method only needs to loop K times. The principle is to constantly clear n binary representation of the rightmost 1, while accumulating counters, until n is 0, the code is as follows

int int N) {    int c =0  ;      for (c =0; n; + +c)    {        &= (n-1//  clears the lowest bit of 1    }    return C;}

Why is n &= (n–1) able to erase the rightmost 1? Because from the binary point of view, N is equivalent to the lowest bit of n-1 plus 1. For example, 8 (1000) = 7 (0111) + 1 (0001), so 8 & 7 = (+) & (0111) = 0 (0000), the 8 rightmost 1 is cleared (actually the highest 1, because there is only one 8 in the binary of 1). For example, 7 (0111) = 6 (0110) + 1 (0001), so 7 & 6 = (0111) & (0110) = 6 (0110), the rightmost 7 of the binary representation of 1 (that is, the lowest bit 1) is cleared.

Ext.: http://www.cnblogs.com/graphics/archive/2010/06/21/1752421.html

Algorithm-to find the number of 1 in a binary 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.