How to use Regular Expression In Javascript
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.
function isSparse(num) {
return !/(11)/.test(num.toString(2));
}
console.log(isSparse(6));
console.log(isSparse(72));
Output
false true
JavaScript Program to Check if a Number is Sparse or Not
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:
Table of Content
- 1. By Using Bitwise Operators
- 2. By converting to Binary String
- 3. Using Regular Expression
- 4. By Manually Iterating Through Binary Digits