A discussion of parity between C + + and arithmetic

Source: Internet
Author: User

& Bitwise AND if two corresponding bits are 1, then the result value of this bit is 1, otherwise 0

int fun (int n) {      return  (n&1);       Returns 1 for odd, 0 for even.  }

According to the arithmetic rules of bitwise AND, if two corresponding bits are 1, then the result value is 1, otherwise 0. The key to N&1 is the last bits, which determines whether n is an odd or even number. That is, N and 1 bitwise operations regardless of how many bits of N, as long as the last one is 1, the last one is 1 means that n must be an odd number (2k+...+1 must be odd), at this time with 1 bitwise AND operation return value is 1, otherwise the return value is 0, that is, n is even. Bit operations are faster than% operations and learn to use bits and arithmetic to judge parity.

In short remember: n&1 return value is 1 means n is odd, the return value is 0 means n is even.

A discussion of parity between C + + and arithmetic

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.