I have been given this sample code for some exercises, and it shows how to find whether an integer is odd or even.
int x = 4; if ( (x & 1) == 0 ) { System.out.println("even"); } else { System.out.println("odd"); } But I dont understand why you do ' x & 1 '. What's the purpose of that?
06 Answers
In the binary representation of a number, any number with its least significant bit set to 0 is even. It would also be helpful to know what the & operator does.
For example 5 = 0101 (binary) and 1 = 0001 (binary). In this case, it compares 0101 with 0001.
You compare it bitwise, so the first bit would be 1 & 0 = 0. The second bit is 0 & 0 = 0. The third bit is 0 & 0 = 0. The last bit is 1 & 1 = 1.
So 5 & 1 = 0001, which is 1 in decimal. 1 == 0 evaluates to false for x = 5.
For all other even numbers, the least significant digit is 0, so any even number & 1 will always evaluate to 0.
That is because & performs a bitwise AND operation:
if ( (x & 1) == 0 ) Your code is as good as saying, print "Odd" if last binary digit of x is 1.
And it will work because all odd numbers will always have 1 as their last binary digit.
Consider this:
1 is 0001 in binary. 2 is 0010 in binary. When (0001 & 0010) only those positions with both matched with 1 will remained as 1, which means:
0001 & 0010 gives you 0000 (0) // 1 & 2 = 0 Look at this pattern:
0001 & 0001 = 1 //1 & 1 = 1 (is odd) 0010 & 0001 = 0 //2 & 1 = 0 (is even) 0011 & 0001 = 1 //3 & 1 = 1 (is odd) 0100 & 0001 = 0 //4 & 1 = 0 (is even) 0101 & 0001 = 1 //5 & 1 = 1 (is odd) 0110 & 0001 = 0 //6 & 1 = 0 (is even) It's a bitwise AND operation between the binary representation of the two numbers. Odd numbers always have their 1 bit set. Even numbers do not.
So, the ampersand AND == 0 is true for even numbers, but not for odd ones.
It evaluates the variable's binary value
Let's say x = 6 (110 in binary) and y = 7 (111)
Since we know that 1&0=0 and 1&1=1 (or true&false=false and true&true=true)
x & 1 == 0 // evaluates to true if x is even because 110 &001 ---- 000 y & 1 == 0 // evaluates to false because 111 &001 ---- 001 The LSB of a binary number is holding the information about Parity,
any odd numbers has LBS==1 and any even has LSB==0
so when you do a bitwise and you are multiplying bit by bit against 1, the porpouse of this is to clear all other bits but leaving the LSB just like it is (that is why multpling by 1)
A binary number can be easily identified if it's odd or even just by looking at least significant bit, wheather it is set or not(1 or 0). If least significant bit is 1 then that's an odd number else it's an even. Just check (number % 10) if true, its odd number, else even number.
