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