How to check if a number is sparse number in C

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. 
*/
 
#include <stdio.h>
#include <stdbool.h>
 
bool is_sparse(int n) { 
    int result = n & (n >> 1);
     
    if (result == 0)
      return true;
     
    return false;
}
 
int main()
{
  
  printf("%d\n", is_sparse(72));
  printf("%d\n", is_sparse(5));
  printf("%d\n", is_sparse(36));
  printf("%d\n", is_sparse(305));
 
  return 0;
}
 
 
 
 
/*
run:
 
1
1
1
0
 
*/

 



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