How to check if a number is sparse number in Node.js

1 Answer

0 votes
/*
    If there are no two consecutive 1s in a number binary representation, 
    it is Sparse. 5 (101) is sparse, 6 (110) is not. 
*/
class Number {
    is_sparse(n) {
        let result = n & (n >> 1);
            
        if (result == 0)
          return true;
            
        return false;
    }
}
function main(args) {
    const obj = new Number();
      
    console.log(obj.is_sparse(72));
    console.log(obj.is_sparse(5));
    console.log(obj.is_sparse(36));
    console.log(obj.is_sparse(305));
}

main();




/*
run:
  
true
true
true
false
  
*/

 



answered Oct 11, 2021 by avibootz
...