Use the & symbol to determine the parity of a number, and determine whether a number (x) is 2 of the n-th square

Source: Internet
Author: User

Judging the parity of a number is seen in C + + primer problem sets, and it feels interesting:

Suppose there is an integer x ha, assuming that

Then there are:

if (x&1)
    cout<< "odd" <<endl;
else
   cout<< "even" <<endl;

Take eight-bit binary as an example: 1 of the binary is 00000001 then an odd binary last must be 1, then an odd and 1 want to be 1, and conversely, even the last digit of the binary must be 0, so, an even number and a 1 want with a certain 0;


The return value of the following function (Microsoft) is calculated---------The number of statistics 1
int func (int x)
{
int countx = 0;
while (x)
{
countx++;
x = x& (x-1);
}
return countx;
}
Assume x = 9999
10011100001111
Answer: 8
Idea: Convert x into 2, and see the number of 1.
Note: each time x = x& (x-1) is executed, the rightmost 1 is changed to 0 when x is represented by binary, because x-1 will change the bit (x is the rightmost 1 in binary notation) to 0. (assuming that the bit is the K-bit, minus 1, after the bit all becomes 1, but because the bit is the rightmost 1, so the K-bit of x is all 0, and the K-bit of x-1 is 0, from 1 to K-1 is 1, and the result of the bitwise AND of the 1~K-1 bit is 0. )
So one of the uses of the expression:

1: Turning the lowest bit of 1 into 0, this interpretation is not difficult to understand.

The second use of the expression is:
2: When x is odd,,x=x& (x-1) has the same value as x=x-1; when X is the N-Power of 2, the result is 0, which can be used to quickly determine whether a number is a 2 n-th square.
Determines whether a number (x) is 2 of the n-th square
#include <stdio.h>
int func (int x)
{
if ((x& (x-1)) = = 0)
return 1;
Else
return 0;
}

int main ()
{
int x = 8;
printf ("%d\n", func (x));
}
Note:
(1) If a number is a 2 of the N-square, then the number in binary representation of its highest bit is 1, the rest is 0, and then use the above idea is easy to think.


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.