Trusted answers to developer questions

abhilash

You can check if a number is even or odd in many different ways, including through the use of **bitwise operators**.

Example 1:

- Given number = 24
- Output = even

Example 2:

- Given number = 13
- Output = odd

First, let’s convert the following numbers to binary representation.

Number | Binary representation |
---|---|

24 | “1100`0` ” |

22 | “1011`0` ” |

13 | “110`1` ” |

7 | “11`1` ” |

When we observe the least significant bit (the rightmost bit), we find the following observations:

- Even numbers have
`0`

as their least significant bit in binary form. - Odd numbers have
`1`

as their least significant bit in binary form.

Hence, one algorithm to find if a number is even or odd using bitwise operations is as follows:

- Do a bitwise AND (
`&`

) with the given number and`1`

. - If the result of the above step is
`1`

, then the number is an odd number. - Otherwise, the number is an even number.

The code to check if a number is odd or even using `&`

is provided below.

import java.util.Scanner; public class Main{ private static void OddOrEven(int n){ if((n & 1) == 1) System.out.println("The number " + n + " is an odd number"); else System.out.println("The number " + n + " is an even number"); } public static void main(String[] args){ Scanner scanner = new Scanner(System.in); int number = scanner.nextInt(); OddOrEven(number); } }

Enter the input below

RELATED TAGS

bitwise

java

communitycreator

CONTRIBUTOR

abhilash

RELATED COURSES

View all Courses

Keep Exploring

Related Courses