How would I do this in Java? Find if a number is divisible by 2, if the last digit is even. (0,2,4,6,8) Example: 128 is, 129 is not
Check whether the number is even or odd by using bitwise XOR. If the number after bitwise XOR with 1 is equal to the original number + 1, then it is an even number. If not equal, then it is an odd number.
This is the basic formula: dividend = divisor * quotient + remainder From this equation you can calculate the remainder.
We can divide the number by 2, then check whether the remainder is 0 or not. if 0, then it is even. Otherwise we can perform AND operation with the number and 1. If the answer is 0, then it is even, otherwise odd.
A number that is divisible by 2 and generates a remainder of 0 is called an even number. All the numbers ending with 0, 2, 4, 6, and 8 are even numbers. On the other hand, number that is not divisible by 2 and generates a remainder of 1 is called an odd number.
if((n|1)==n)
System.out.println("odd");
else
System.out.println("even");
Reason: number is odd if the LSB is 1, and even otherwise. When n|1 is done, LSB of odd stays the same so the resulting number is not changed, while LSB of a even number becomes 1, thus changing the number.
see if the the right most bit is 1 then its not, by using bitwise operators
perform logical and with (for example)
yourNumber & 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With