Next higher number with same number of set bits in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that finds the next greater integer having one more number of set bits.

Let's see the steps to solve the problem.

  • Initialise the number n.

  • Write a function get the count of number of set bits.

  • Initialise the iterative variable with n + 1.

  • Write an infinite loop.

    • Check for the number of set bits for numbers equal to the number of set bits of n.

    • Return the number when you find it.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getSetBitsCount(int n) {
   int count = 0;
   while (n) {
      if (n % 2 == 1) {
         count += 1;
      }
      n /= 2;
   }
   return count;
}
int getNextGreaterElementWithSameSetBits(int n) {
   int setBitsCount = getSetBitsCount(n);
   int i = n + 1;
   while (true) {
      if (setBitsCount == getSetBitsCount(i)) {
         return i;
      }
      i += 1;
   }
}
int main() {
   int n = 124;
   cout << getNextGreaterElementWithSameSetBits(n) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result.

143

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

raja
Published on 01-Jul-2021 06:09:18
Advertisements