

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Next greater integer having one more number of set bits in C++
We are given a number n, we have to find the number that is greater than n with one more set bit than n in its binary representation.
The digit 1 in the binary representation is called set bit.
Let's see an example.
Input
124
Output
125
Algorithm
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 greater than n.
Return the number when you find it.
Implementation
Following is the implementation of the above algorithm in C++
#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 + 1 == 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.
125
- Related Questions & Answers
- Previous smaller integer having one less number of set bits in C++
- Next higher number with same number of set bits in C++
- Find next greater number with same set of digits in C++
- Count of divisors having more set bits than quotient on dividing N in C++
- Count set bits in an integer in C++
- Largest number less than X having at most K set bits in C++
- Print numbers having first and last bits as the only set bits
- Find next Smaller of next Greater in an array in C++
- Next Greater Element in C++
- Java Program to Count set bits in an integer
- Python Program to Count set bits in an integer
- Number of integers with odd number of set bits in C++
- Python program to reverse bits of a positive integer number?
- Java program to reverse bits of a positive integer number
- Program to get next integer permutation of a number in C++
Advertisements