After Java Puzzlers.
class Test { public boolean isOddWrong1(int i) { // -1 % 2 returns not 1 but -1 return i % 2 == 1; } public boolean isOddCorrect1(int i) { // Get a new angle on test return i % 2 != 0; } public boolean isOddCorrect2(int i) { // the best return (i & 1) != 0; } public static void main(String[] args) { Test t = new Test(); System.out.println("isOddWrong1(-1)=" + t.isOddWrong1(-1)); System.out.println("isOddCorrect1(-1)=" + t.isOddCorrect1(-1)); System.out.println("isOddCorrect2(-1)=" + t.isOddCorrect2(-1)); } }
Leave a Reply