How to useBitwise & Operator in Javascript
A better solution is to use bitwise operators. We need to check whether the last bit is 1 or not. If the last bit is 1 then the number is odd, otherwise the number is even.
Syntax:
a & b
Example: In this example, we are using the bitwise & operator to find given number is even or odd.
function checkOddOrEven(n) {
if (n & 1 == 1) {
return "Number is odd";
}
return "Number is even";
}
console.log(checkOddOrEven(12));
console.log(checkOddOrEven(121));
Output
Number is even Number is odd
JavaScript Program to Check if a Number is Odd or Even
We are going to learn how to check whether the number is Even or Odd using JavaScript. In the number system any natural number that can be expressed in the form of (2n + 1) is called an odd number and if the number can be expressed in the form of 2n is called an even number.
In other words, Those numbers that are completely divisible by 2 (give the remainder 0 after dividing by 2) are known as even numbers and those which divided by 2 and leave a reminder 1 are called odd numbers.
Even = {2k : k ∈ Z}
Odd = {2k + 1 : k ∈ Z}
where k is an integer.
Example:
Input: 2
Output: Even number
Input: 41
Output: Odd Number
There are several methods that can be used to Check if a Number is Odd or Even, which are listed below:
Table of Content
- Approach 1: Using the modulo Operator
- Approach 2: Using Bitwise & Operator
- Approach 3: Using Bitwise OR Operator (|)
- Approach 4: Using Ternary Operator