Alternative solution for problem 5.3 from 'Cracking Coding Interview" book
0 Answers
Alternative solution for problem 5.3 from 'Cracking Coding Interview" book
| Flag | PURGE
Just something I cannot not share :) I think we can avoid loops in this problem:
uint64_t GetNext_NP(uint64_t n)
{
if (n == 0 || n == -1ull)
{
return 0;
}
uint64_t first_one_mask = ((n ^ (n - 1) ) + 1) >> 1;
uint64_t first_zero_mask = ((n ^ (n + first_one_mask)) & (n + first_one_mask));
n |= first_zero_mask;
first_zero_mask >>= 1;
n &= ~first_zero_mask;
n &= ~(first_zero_mask - 1);
n |= (first_zero_mask / first_one_mask) - 1;
return n;
}
Email me when people comment.
Email me when people comment.
Loading...
An error occurred in subscribing you.
Email me when people comment.
Email me when people comment.
Loading...
An error occurred in subscribing you.
CareerCup is the world's biggest and best source for software engineering interview preparation. See all our resources.