Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing oddity of an integer with the modulo operator

Tags:

java

modulo

The following code snippet does not test oddity correctly:

public static boolean isOdd(int i) {    return i % 2 == 1; } 

I read in the web that I should do it the following way:

public static boolean isOdd(int i) {    return i % 2 != 0; } 

Why is this?

like image 387
casaout Avatar asked May 17 '13 12:05

casaout


2 Answers

Might be because (i % 2) != 0 works for both positive and negative numbers

like image 74
Stochastically Avatar answered Sep 19 '22 13:09

Stochastically


Because when i is negative --> (-1) % 2 == -1

like image 20
johnchen902 Avatar answered Sep 20 '22 13:09

johnchen902