Saturday 21 January 2012

Checking the oddity of a integer number in java

From Jashua Bloch's "Java Puzzlers" book.

// Wrong way to check the oddity
public boolean isOdd(int num){
return (num % 2 == 1) // Broken- for all -ve odd numbers
}

The reason for this would be clear once you read about modulus operator.

// Right Solution
public boolean isOdd(int num){
return (num % 2 != 0)
}

// Much better and Faster
public boolean isOdd(int num){
return (num & 1)
}

No comments:

Post a Comment