Open In App

JavaScript Program to Check if a Number is Odd or Not using Bit Manipulation

Last Updated : 03 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, bit manipulation is the process of manipulating individual bits in a number for various operations. In this article, we will explore two approaches using bit manipulation to Check whether a number is odd or not.

Below are the approaches to Check if a number is odd or not using bit manipulation:

Examples:  

Input: N = 11 
Output: Odd

Input: N = 10 
Output: Even 

Using bitwise AND with 1

In this approach, we use the bitwise AND (&) operator with 1 to check the least significant bit of the number. If the result is 1, the number is odd; otherwise, it is even.

Example: Implementation to use bitwise AND with 1 to Check if a number is odd or not using bit manipulation.

JavaScript
let num = 2;
if (num & 1) {
    console.log(num + " is odd");
} else {
    console.log(num + " is even");
}

Output
2 is even

Time Complexity: O(1)

Space Complexity: O(1)

Using bitwise XOR with 1

In this approach, we are using bitwise XOR (^) operator with 1 to toggle the least significant bit of the number. If the result is 1, the number is odd; otherwise, it is even.

Example: Implementation to use bitwise XOR with 1 to Check if a number is odd or not using bit manipulation.

JavaScript
let num = 11;
if (num ^ 1) {
    console.log(num + " is odd");
} else {
    console.log(num + " is even");
}

Output
11 is odd

Time Complexity: O(1)

Space Complexity: O(1)

Using Bitwise Right Shift

We can also use bitwise right shift (>>) operation by 1 bit and then check the LSB. If it’s 1, the number is odd; otherwise, it’s even.

Example: This example shows the implementation of the above-explained approach.

JavaScript
function isOdd(num) {
    return (num >> 0) & 1 === 1;
}

let x = 13;

if (isOdd(x)) {
    console.log(`${x} is odd`);
}
else {
    console.log(`${x} is even`);
}

Output
13 is odd

Time Complexity: O(1)

Space Complexity: O(1)


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads