Find out how many 1 different solutions in a number bits

Source: Internet
Author: User

* Returns the number of 1 in a binary representation of a number. *

#include <stdio.h>int main () {    unsigned int i;    &NBSP;SCANF ("%d", &i);     printf ("%d binary expression has  %d  1", i,count_one_bits (i));     return 0;} Int  count_one_bits (unsigned int m) {    int n,count;     //  return  1 number of digits     n = m;    count =  0;    while (n % 2 == 0)          n = n / 2;    while (n % 2 == 1)      {        count++;         do        {             if  (n != 0)                 n = n / 2;             else                 break;        }         while (n % 2 == 0);     }      return count;}

This is the most easy way to think of, and constantly in addition to 2 modulo 2 to take the remainder, the following gives another method (omit part of the statement)

... i = 32;while (i--) {if (num & 1 = = 1) count++; num = num>>1;}

This method is shifted to the right, so that the lowest bits & 1 are judged, and a more efficient method

int count_one_bit (int num) {int count = 0;    while (num) {count++; As long as a number is not 0, then there is at least one 1 num in the binary expression = num & (num-1);//The statement is not executed once, in fact, the lowest bit of the number of a 1 to 0} return count;


This article is from the "Knock Code good Sleep zzz" blog, please be sure to keep this source http://2627lounuo.blog.51cto.com/10696599/1703820

How many different solutions to 1 in a number bits

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.