Count the number of 1 in the binary

Source: Internet
Author: User

This article provides three ways to calculate the number of 1 in a binary representation of a number, respectively. Methods and explanations are shown in Count1, Count2, Count3 function respectively.

Only Count1 can not meet the negative demand (will die loop in), the other two will be able to operate within 32b positive negative numbers.

Count1: Each time x is last to 1, see if it is 1, then move X to the right

Count2: Start the variable y from 1 to X, and then move Y to the left each time, similar to the previous method

Count3: Each time x&= (x-1) can change the rightmost one 1 to 0;

The method is applied: e.g. how to use a statement to determine whether an integer is 2 of the power of the whole number?

/********************///@Discription: Count The number of ' 1 ' in binary number//@Author: Rachel Zhang//@Create date:2012-5-22/********************/#include"stdio.h"intCount1 (intx) {    intC=0;  while(x) {C+=x&1; X>>=1; }    returnC;}//Bug: When x=0x80000000 (negative), x>>1 to guarantee or negative, so not 0x40000000, but =0xc0000000//i.e input-2147483648 (0x80000000), x>>1=-107374124 (0xc0000000), not 2^30 (0x40000000)//so the final 0xff will lead to a dead loop .intCount2 (intx) {    intC=0; unsignedinty=1;  while(y) {c+=x&y?1:0; Y<<=1; }    returnC;}//problem: Do not know the number of x digits, will cause some redundant operations, but it's okay, 32-bit PC up to 32 times//It's not a problem.intCount3 (intx) {    intC=0;  while(x) {x&=x-1; C++; }    returnC;}intMain () {intx;  while(SCANF ("%d", &x)! =EOF) {printf ("%d\n%d\n%d\n", Count1 (x), Count2 (x), Count3 (x)); }    return 0;}


SOURCE title: http://zhedahht.blog.163.com/blog/static/25411174200731844235261/

Count the number of 1 in the binary

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.