Find the number of 1 in a binary binary (optimized). Determine if a number is 2 of the n-th square

Source: Internet
Author: User

Find the number of 1 in a binary binary:

General Method :

#include <stdio.h>

#include <stdlib.h>

int count_one_bits (unsigned int value)

{

int count = 0;

for (int i = 0; i <; i++)

{

if      (value & 1 = = 1) (%2 equivalent to &1)

{

count++;

}

value = value >> 1; (move right one equivalent to 2)

}

return count;

}

int Main ()

{

unsigned int value= 0;

scanf ( "%d" , &value);

int ret = count_one_bits (value);

printf ( "%d\n" , ret);

System ( "pause" );

return 0;

}


650) this.width=650; "src="/e/u261/themes/default/images/spacer.gif "style=" Background:url ("/e/u261/lang/zh-cn/ Images/localimage.png ") no-repeat center;border:1px solid #ddd;" alt= "Spacer.gif"/>

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/7D/8F/wKioL1bq0_zwLZmZAAB6YBz1nPk838.png "title=" Untitled. png "alt=" Wkiol1bq0_zwlzmzaab6ybz1npk838.png "/>


Optimization:

#include <stdio.h>

#include <stdlib.h>

int count_one_bits (unsigned int value)

{

int count = 0;

while (value )//value enters a loop if nonzero

{

count++; Because value is not 0, there is at least one 1 in the binary

value = value & (value -1); N and n& (n-1) binary is always a difference of 1


}

return count;

}

int Main ()

{

unsigned int value= 0;

scanf ( "%d", &value);

int ret = count_one_bits (value);

printf ( "%d\n", ret);

System ( "pause");

return 0;

}

To ask a number of books is not 2 of the n-th square:

#include <stdio.h>

int main ()

{

int num=0;

scanf ("%d", &num);          

if (value & (value -1)) ==0);

printf ("yes\n");

Else

printf ("no\n");

return 0;

}


This article is from the "11132019" blog, please be sure to keep this source http://11142019.blog.51cto.com/11132019/1752371

Find the number of 1 in a binary binary (optimized). Determine if a number is 2 of the n-th square

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.