- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 higher number with same number of set bits in C++
We are given a number n, we have to find the number that is greater than n with same number of set bits as n in its binary representation.
The digit 1 in the binary representation is called set bit.
Let's see an example.
Input
124
Output
143
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 equal to the number of set bits of n.
Return the number when you find it.
- Increment the number.
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 == 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
- Related Articles
- Program to find higher number with same number of set bits as n in Python?
- Maximum number of contiguous array elements with same number of set bits in C++
- Find next greater number with same set of digits in C++
- Next greater integer having one more number of set bits in C++
- Maximum sum by adding numbers with same number of set bits in C++
- Number of integers with odd number of set bits in C++
- Check if a number has same number of set and unset bits in C++
- Minimum number using set bits of a given number in C++
- Next higher number using atmost one swap operation in C++
- Prime Number of Set Bits in Binary Representation in C++
- Find the next lowest number higher than a certain number in MySQL?
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- Binary Number with Alternating Bits in C++
- Minimum flips required to maximize a number with k set bits in C++.
- Find the largest number with n set and m unset bits in C++

Advertisements