The beauty of programming a number of binary representations of 1 in number

Source: Internet
Author: User

Here are 3 solutions to be introduced

The first kind; (Conventional solution)

The number is represented in the computer by binary, so it can be continuously use the number n to divide by 2

Code Listing 1:

#include <iostream>using namespace Std;int main (void) {int n,m;    m=0;    cin>>n;        while (n) {if (n%2)//If n cannot be divisible by 2, indicating that the end number of the current n is 1 m++;    n>>=1;    n Shift right 1 bits, i.e. N/2} cout<< m <<endl; return 0;}


The second type: using bit manipulation

&: If A is 1 and B is 1, then a&b is 1, otherwise, A&b is 0

Here initializes the i=0x1;

If the n&i is 1, then the end of N is 1, otherwise 0

Code Listing 2:

#include <iostream>using namespace Std;int main (void) {//Use bit operation, 1 and binary the last one to be performed with (&) operation Int N,I,M;M=0;I=0X1;CIN&G T;>n;while (n) {m+= (n&i); n>>=1;}    cout << M <<endl; return 0;}


Third: Use a different bit operation

If the binary representation of n is 0010 0000, then the second algorithm obviously needs to be improved

Allows N and n-1 to perform a & operation, if n& (n-1) ==0, the above case (the binary representation of N, only one is 0).


Code Listing 3:

#include <iostream>using namespace Std;int main (void) {int n,m;m=0;cin>>n;while (n) {n&= (n-1); m++;} cout << m <<endl;return 0;}


This article is from the "hacker" blog, make sure to keep this source http://anglecode.blog.51cto.com/5628271/1631155

The beauty of programming a number of binary representations of 1 in 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.