language: C (gcc-4.7.2)
date: 236 days 10 hours ago
link:
visibility: public
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <stdio.h>
 
int count_consecutive_ones(int in) {
  int count = 0;
 
  while (in) {
    in = (in & (in << 1));
    count ++;
  }
  return count;
}
 
int count_consecutive_zeros(int in) {
  return count_consecutive_ones(~in);
} 
 
int main(void) {
 
  printf("%d has %d consecutive 1's\n", 0, count_consecutive_ones(0));
  printf("%d has %d consecutive 0's\n", 0, count_consecutive_zeros(0));
 
  /* 00000000 11110000 00000000 00000000 -> If it is 0 then length will be 20 */
  printf("%x has %d consecutive 0's\n", 0x00F00000, count_consecutive_zeros(0x00F00000));
 
  /* 11111111 11110000 11110111 11111111 -> If it is 1 then length will be 12 */
  printf("%x has %d consecutive 1's\n", 0xFFF0F7FF, count_consecutive_ones(0xFFF0F7FF));
 
}