Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cinttypes>
- #include <cstdint>
- #include <cstdio>
- using namespace std;
- static uint8_t count_consecutive_ones(uint64_t);
- static uint8_t count_consecutive_ones_recursive(uint64_t);
- static uint8_t count_consecutive_ones_recursive_sub(uint64_t, uint8_t);
- // http://stackoverflow.com/a/12617595
- static uint8_t count_consecutive_ones(uint64_t in) {
- uint8_t count = 0;
- while (in) {
- in = (in & (in << 1));
- ++count;
- }
- return count;
- }
- static uint8_t count_consecutive_ones_recursive(uint64_t in) {
- return count_consecutive_ones_recursive_sub(in, 0);
- }
- static uint8_t count_consecutive_ones_recursive_sub(uint64_t in, uint8_t acc) {
- if (in == 0) return acc;
- return count_consecutive_ones_recursive_sub((in & (in << 1)), acc + 1);
- }
- int main() {
- uint64_t test_case[] = { 0xffffffffull, 0xfff0ffffull, 0xff0fffffull };
- for (auto&& e: test_case) {
- printf(
- "%" PRIx64 ", no recur: %" PRId8 ", recur: %" PRId8 "\n",
- e,
- count_consecutive_ones(e),
- count_consecutive_ones_recursive(e)
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement