Tuesday, April 01, 2008

checking the oddity of a integer number in java

From Jashua Bloch's "Java Puzzlers" book.

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

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


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





1 comment:

Anonymous said...

This looks great.