Open In App

JavaScript Program to Check if a Number is Sparse or Not

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

A number is considered sparse if it does not have any consecutive ones in its binary representation.

Example:

Input: n=21
Output: True
Explanation: there are no consecutive 1s in the binary representation (10101). Therefore, 21 is a sparse number.

Input: n=22
Output: False
Explanation: there are consecutive 1s in the binary representation (10110). Therefore, 22 is bot a sparse number.

Below are the approaches to check if a number is sparse is not:

1. By Using Bitwise Operators

This approach uses bitwise operators to check if a number is sparse. It works by shifting the binary representation of the number to the left by one position and then performing a bitwise AND operation with the original number. If the result of the bitwise AND operation is greater than 0, it means that there are two consecutive ‘1’s in the binary representation which means the number is not sparse.

Example: Implementation to check if a number is sparse or not using Bitwise Operators.

JavaScript
function isSparse(num) {
    if ((num & (num >> 1)) > 0) {
        return false;
    }
    else {
        return true;
    }
}

console.log(isSparse(10))
console.log(isSparse(6))

Output
true
false

2. By converting to Binary String

In this approach we converts the number to a binary string using toString(2) and then checks if there are any occurrences of ’11’ in the string. If there are no consecutive ‘1’s the number is sparse.

Example: Implementation to check if a number is sparse or not by converting the number to Binary String.

JavaScript
function isSparse(num) {
    const binary = num
    .toString(2);
    return !/11/
    .test(binary);
}

console.log(isSparse(21));
console.log(isSparse(31));

Output
true
false

3. Using Regular Expression

In this approach we are using regular expression to check if the binary representation of the number contains consecutive 1s.

Example: Implementation to check if a number is sparse or not using regular expression.

JavaScript
function isSparse(num) {
    return !/(11)/.test(num.toString(2));
}

console.log(isSparse(6));
console.log(isSparse(72));

Output
false
true



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

Similar Reads