How to use bitwise operators In Javascript
In this approach, we leverage bitwise operators to check the sign of the integer. Specifically, we use the right shift operator (>>) to extract the sign bit and compare it with 0 to determine whether the number is positive, negative, or zero.
Example:
function checkNumber(num) {
if (num === 0) {
return "Zero";
} else if (num >> 31 !== 0) {
return "Negative number";
} else {
return "Positive number";
}
}
// Test cases
console.log(checkNumber(10));
console.log(checkNumber(-5));
console.log(checkNumber(0));
Output
Positive number Negative number Zero
JavaScript Program to Check if a Given Integer is Positive, Negative, or Zero
In this article, we will discuss how we can determine whether the given number is Positive, Negative, or Zero. As we know if the number is less than 0 then it will be called a āNegativeā number if it is greater than 0 then it will be called a āPositiveā number. And if it doesnāt lie between them, then it will be 0.
Example:
Input: 10
Output: Positive number
Input: -12
Output: Negative number
Input: 0
Output: Zero
These are the following ways by which we can find out whether the number is Positive, Negative, or Zero:
Table of Content
- Using if-else statement
- Using ternary operator
- Using switch case
- Using Math.sign()
- Using bitwise operators