How to check if a number is sparse number in Swift

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 {
    func is_sparse(_ n: Int) -> Bool {
        var result : Int
        
        result = n & (n >> 1);
        
        if (result == 0) {
          return true;
        }
            
        return false;
    }
}
func main() {
    let obj: Number = Number();
  
    print(obj.is_sparse(72));
    print(obj.is_sparse(5));
    print(obj.is_sparse(36));
    print(obj.is_sparse(305));

}

main();



/*
run:
   
true
true
true
false
   
*/

 



answered Oct 11, 2021 by avibootz
...