Posts

Showing posts with the label bit-manipulation

Finding the smallest number greater than N with K set bits

Image
Clash 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.