fork(14) download
  1. #include <stdio.h>
  2.  
  3. int count_consecutive_ones(int in) {
  4. int count = 0;
  5.  
  6. while (in) {
  7. in = (in & (in << 1));
  8. count ++;
  9. }
  10. return count;
  11. }
  12.  
  13. int count_consecutive_zeros(int in) {
  14. return count_consecutive_ones(~in);
  15. }
  16.  
  17. int main(void) {
  18.  
  19. printf("%d has %d consecutive 1's\n", 0, count_consecutive_ones(0));
  20. printf("%d has %d consecutive 0's\n", 0, count_consecutive_zeros(0));
  21.  
  22. /* 00000000 11110000 00000000 00000000 -> If it is 0 then length will be 20 */
  23. printf("%x has %d consecutive 0's\n", 0x00F00000, count_consecutive_zeros(0x00F00000));
  24.  
  25. /* 11111111 11110000 11110111 11111111 -> If it is 1 then length will be 12 */
  26. printf("%x has %d consecutive 1's\n", 0xFFF0F7FF, count_consecutive_ones(0xFFF0F7FF));
  27.  
  28. }
Runtime error #stdin #stdout 0.01s 1676KB
stdin
Standard input is empty
stdout
0 has 0 consecutive 1's
0 has 32 consecutive 0's
f00000 has 20 consecutive 0's
fff0f7ff has 12 consecutive 1's