Next greater integer having one more number of set bits

3

Given a positive integer ‘n’ having ‘x’ number of set bits in its binary representation. The problem is to find the next greater integer(smallest integer greater than n), having (x+1) number of set bits in its binary representation.

Examples::

Input : 10
Output : 11
(10)10 = (1010)2
is having 2 set bits.

(11)10 = (1011)2
is having 3 set bits and is the next greater.

Input : 39
Output : 47

Approach: Following are the steps:

  1. Find the position of the rightmost unset bit(considering last bit at position 0, second last bit at position 1 and so on) in the binary representation of n.
  2. Let the position be represented by pos.
  3. Set the bit at position pos. Refer this post.
  4. If there are no unset bits in the binary representation, then perform bitwise left shift by 1 on the given number and then add 1 to it.

How to get the position of rightmost unset bit?

  1. Perform bitwise not on the given number(operation equivalent to 1’s complement).Let it be num = ~n.
  2. Get the position of rightmost set bit of num.
// C++ implementation to find the next greater integer
// with one more number of set bits
#include <bits/stdc++.h>

using namespace std;

// function to find the position of rightmost
// set bit. Returns -1 if there are no set bits
int getFirstSetBitPos(int n)
{
    return (log2(n&-n)+1) - 1;
}

// function to find the next greater integer
int nextGreaterWithOneMoreSetBit(int n)
{
    // position of rightmost unset bit of n
    // by passing ~n as argument
    int pos = getFirstSetBitPos(~n);
    
    // if n consists of unset bits, then
    // set the rightmost unset bit
    if (pos > -1)
        return (1 << pos) | n;
        
    //n does not consists of unset bits    
    return ((n << 1) + 1);    
}

// Driver program to test above
int main()
{
    int n = 10;
    cout << "Next greater integer = "
          << nextGreaterWithOneMoreSetBit(n);
    return 0;
} 

Output:

Next greater integer = 11

This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



3 Average Difficulty : 3/5.0
Based on 2 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.