"Java" odd even judgment

Source: Internet
Author: User

Judging method (odd):

Error judgment method: Judge by A%2==1 . (Cause: Negative odd to 2 the result of the remainder is-1)

Correct judgment Method: (1) through a%2! =0 to judge.

(2) Judging by (a&1) ==1 . (Recommended use, bit operation, better performance)

Java code:

public class Test {public static void main (string[] args) {int[] a = {0, 11,-11, 20,-20}; SYSTEM.OUT.PRINTLN ("———— use" a%2!=0 "to Judge ————"); for (int i:a) {System.out.println (i + "+ oddoreven (i));} SYSTEM.OUT.PRINTLN ("———— use" (a&1) ==1 "Judgment ————"), for (int i:a) {System.out.println (i + "+ oddoreven (i));}} public static String OddOrEven (int a) {if (a% 2 = 0) {return "odd";} else {return "even";}} Public String oddOrEven2 (int a) {if ((A & 1) = = 1) {return "odd";} else {return "even";}}}

  

———— use "a%2! =0" to determine ———— 0 is even 11 is odd -11 is odd 20 is even -20 is even ———— use "(A&1 = =1"judgment ———— 0 is even 11 is odd -11 is odd 20 is even -20 is even
Test

Expand:

This time, when writing code, if the use of the residual symbol%, pay attention to the situation of negative numbers.

"Java" odd even judgment

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.