Advertisement
Guest User

Count consecutive ones

a guest
Apr 22nd, 2017
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #include <cinttypes>
  2. #include <cstdint>
  3. #include <cstdio>
  4. using namespace std;
  5. static uint8_t count_consecutive_ones(uint64_t);
  6. static uint8_t count_consecutive_ones_recursive(uint64_t);
  7. static uint8_t count_consecutive_ones_recursive_sub(uint64_t, uint8_t);
  8.  
  9. // http://stackoverflow.com/a/12617595
  10. static uint8_t count_consecutive_ones(uint64_t in) {
  11.   uint8_t count = 0;
  12.   while (in) {
  13.     in = (in & (in << 1));
  14.     ++count;
  15.   }
  16.   return count;
  17. }
  18.  
  19. static uint8_t count_consecutive_ones_recursive(uint64_t in) {
  20.   return count_consecutive_ones_recursive_sub(in, 0);
  21. }
  22.  
  23. static uint8_t count_consecutive_ones_recursive_sub(uint64_t in, uint8_t acc) {
  24.   if (in == 0) return acc;
  25.   return count_consecutive_ones_recursive_sub((in & (in << 1)), acc + 1);
  26. }
  27.  
  28. int main() {
  29.   uint64_t test_case[] = { 0xffffffffull, 0xfff0ffffull, 0xff0fffffull };
  30.   for (auto&& e: test_case) {
  31.     printf(
  32.       "%" PRIx64 ", no recur: %" PRId8 ", recur: %" PRId8 "\n",
  33.       e,
  34.       count_consecutive_ones(e),
  35.       count_consecutive_ones_recursive(e)
  36.     );
  37.   }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement