Reputation: 11
I came across the following C++ solution for finding the smallest number greater than n that has the same number of 1's in its binary representation
int solution(int n) {
int pivot = n & -n;
int before = ((n ^ (n + pivot)) / pivot) >> 2;
return (n + pivot) | before;
}
However, I don't fully understand the purpose of the /pivot and >> 2 operations in the code.
Could someone explain what these operations are doing, and why they are necessary in this algorithm?
I understand what pivot is doing in the following solution (it's used to isolate the least significant set bit of n), and I also get the purpose of dividing by pivot—it's to adjust the flipped bits to the smallest bit value. However, I’m confused about the reason for the >> 2 (right shift by 2) operation in this code
Upvotes: 1
Views: 64