In this post, we'll discuss a simple trick to make your code a little faster. Checking whether a number is even or odd is achieved most commonly (especially by beginners) by using: if(number%2==0). However, the following code :
The above code uses the bitwise '&' operator. A bitwise operator renders the code a little more faster as it operates directly at the binary level (although it no longer makes any difference with the advent of dual core processors). It's proximity to the low - level, the hardware speeds up the operation being performed. Now, let's have a look at how the '&' operator works in the above code.
The & operator is the same as the AND logic gate, according to which true (1) and true (1) evaluate to true (1), while false (0) and true(1)/false(0) always evaluates to false (0). Now when the '&' operator is used with two integers, it performs the and operation on the binary values of both the numbers.
Here's the code:
Let's take a look at the binary form of the first ten numbers :
Notice the rightmost digit in the binary representation : it is 1 when the number is odd and 0 when it is even.
On performing the '&' operation with 1, the following two cases will arise :
Now, 00000001 is the binary form of 1 and 00000000 corresponds to, of course, 0.
Therefore 1 & odd number would return 1, while 1 & even number would return 0.
Tuesday, 9 September 2014