isOdd?

Tags:

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));
    }
}

Comments

2 responses to “isOdd?”

  1. nobody Avatar
    nobody

    음수는 홀짝 의미가 없잖아. 저건 리턴 밸류 문제가 아니라 아예 저기서 음수라고 뭐라고 하는 처리를 하거나 아예 call 하기 전에 처리를 해줘야 될 것 같은데…

  2. MKSeo Avatar
    MKSeo

    odd number의 정의는 원래 음수도 돼.
    http://mathworld.wolfram.com/OddNumber.html

    근데 intuitive 하게 보면 음수를 넣는 자체가 말이 안되긴 해. 이거 원래 Java Puzzlers 라고 자바 퍼즐 문제가 모아진 책이라서 문제 자체가 좀 아슬아슬한 모서리의 것이 나오는 면이 있어.

Leave a Reply

Your email address will not be published. Required fields are marked *