Saturday 17 January 2015

Check number even or odd without using modulo operator

Check given number is even or odd without using modulo operator.
for this we use & operator.
  if any number is odd it must have right most bit 1.
example:
int i=5;
binary form i= 0101
now use & operator
int j=i&1;[0101&1]//
here j have 0001;

public class EvenandOddNumber {
public static void main(String[] args) {
    int i=5;
    int j=i&1;
    if(j>0){
        System.out.println("odd");
    }
    else {
        System.out.println("even");
    }
}
}

No comments:

Post a Comment