Sunday, 1 May 2016

Check if the number is odd ?


Solution #1. Check if num % 2 == 0
boolean isOdd = (num % 2 == 1);

Problem. It will not return correct result for -ve number


Solution #2. Same approach but use absolute value of num
if(num<0) {
   num = -(num);
}
boolean isOdd = (num % 2 == 1);


Solution #3. Check using bitwise & with 1 (Binary = 000000...1)
boolean isOdd = (num & 1) != 0;

Example
21 = 10101
  1 = 00001
----------------
        00001  => Odd, Yes.

Fastest and most optimized solution.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.