parity judgment of int value in Java

Source: Internet
Author: User

Actually this comes from the Java puzzlers, written to remember it.

I%2==1 is the usual method of judging odd numbers, which has the disadvantage that when I is negative, the result is wrong, because in Java, the result of the% operation and the left operand have the same symbol.

There are two ways to improve

1, i%2!=0, so that even the negative odd number can be correctly judged, but how much gives people the feeling of fluke.

2, I&1!=0, the last odd number is always 1, so and 1 of the binary format to and, the result must be 1, and the positive and negative are all 12 in the format of the 0 and dropped. This is a recommended method in the book.

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.