How to check if a number is sparse number in Scala

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 {
    def is_sparse(n: Int): Boolean = {
        var result = n & (n >> 1);
            
        if (result == 0)
          return true;
            
        return false;
    }
}
 
object Main {
    def main(args: Array[String]): Unit = {
        var obj: Number = new Number();
     
        println(obj.is_sparse(72));
        println(obj.is_sparse(5));
        println(obj.is_sparse(36));
        println(obj.is_sparse(305));
    }
}
 
 
 
 
/*
run:
  
true
true
true
false
  
*/

 



answered Oct 10, 2021 by avibootz
edited Oct 12, 2021 by avibootz
...