Advertisement
STANAANDREY

bit segments

Oct 26th, 2022
851
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.34 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. int segments(unsigned n) {
  4.   int r = 1, prevBit = n & 1, bit;
  5.   for (int i = 1; i < sizeof(n) * 8 - 1; i++) {
  6.     bit = (n >> i) & 1;
  7.     r += (bit != prevBit);
  8.     prevBit = bit;
  9.   }
  10.   return r;
  11. }
  12.  
  13. int main() {
  14.   unsigned n;
  15.   printf("n="); scanf("%u", &n);
  16.   printf("segments: %d\n", segments(n));
  17.   return 0;
  18. }
  19.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement