The beauty of programming 1 -- the number of 1 in the binary representation of a number, the beauty of Binary

Source: Internet
Author: User

The beauty of programming 1 -- the number of 1 in the binary representation of a number, the beauty of Binary

Three solutions are introduced here.

First; (conventional solution)

The number is represented in binary in the computer, so the number n can be used consecutively to divide 2

Code 1:


<Span style = "font-size: 14px;" >#include <iostream> using namespace std; int main (void) {int n, m; m = 0; cin> n; while (n) {if (n % 2) // if n cannot divide 2, the end of the current n is 1 m ++; n >>= 1; // n shifts 1 to the right, that is, n/2} cout <m <endl; return 0 ;}</span>


Second: bitwise operations

&: If a is 1 and B is 1, a & B is 1. Otherwise, a & B is 0.

Here I = 0x1 is initialized;

If n & I is 1, the end of n is 1; otherwise, it is 0.

Code 2:



<Span style = "font-size: 14px;" >#include <iostream> using namespace std; int main (void) {// bit operation, 1. the last bit of the binary is used to calculate the int n, I, m; m = 0; I = 0x1; cin> n; while (n) {m + = (n & I); n >>= 1 ;}cout <m <endl; return 0 ;}</span>


Third: use another bit operation

If the binary value of n is 0010 0000, the second algorithm needs to be improved.

Allows n and n-1 to perform the & operation. If n & (n-1) = 0, it is the above case (only one of n's binary representation is 0 ).


Code 3:


<span style="font-size:14px;">#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;}</span>


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.