Finding the smallest number greater than N with K set bits

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


Finding the smallest number greater than N with K set bits



Given a number N, the objective is to find the smallest number greater than N with K set bits in its binary representation.



For example,



N = 1, K = 5 gives 31,



N = 12, K = 2 gives 17



I tried an easy but inefficient approach is simply brute force: count the number of 1s in n, and then increment (or decrement) until we find a number with the same number of 1s.



Any help will be appreciated, thanks.









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Arduino Mega cannot recieve any sketches, stk500_recv() programmer is not responding

Visual Studio Code: How to configure includePath for better IntelliSense results

C++ virtual function: Base class function is called instead of derived