How to check if a number is sparse number in Java

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. 

public class MyClass {
    public static boolean is_sparse(int n) { 
        int result = n & (n >> 1);
          
        if (result == 0)
          return true;
          
        return false;
    }
    public static void main(String args[]) {
        System.out.println(is_sparse(72));
        System.out.println(is_sparse(5));
        System.out.println(is_sparse(36));
        System.out.println(is_sparse(305));
    }
}


  
  
/*
run:
  
true
true
true
false
  
*/

 



answered Oct 10, 2021 by avibootz
...