Skip to content

Instantly share code, notes, and snippets.

@kartikkukreja
Last active January 30, 2016 04:46
Show Gist options
  • Save kartikkukreja/c3df6f4a63faa3e7fa44 to your computer and use it in GitHub Desktop.
Save kartikkukreja/c3df6f4a63faa3e7fa44 to your computer and use it in GitHub Desktop.
Next higher number containing equal set bits
#include <iostream>
#include <bitset>
using namespace std;
// used char for illustration, use int in practice
typedef unsigned char uint;
const unsigned int SIZE = sizeof(uint) * 8;
void printBitRepresentation(uint x) {
cout << bitset<SIZE>(x) << endl;
}
uint getNextHigherNumberContainingEqualSetBits(uint x) {
if (x == 0) return 0;
uint a = x & -x;
uint b = a + x;
uint r = b | (((x ^ b) >> 2) / a);
return r;
}
void generateAllSubsets(uint start) {
printBitRepresentation(start);
for (uint cur = getNextHigherNumberContainingEqualSetBits(start); cur > start; cur = getNextHigherNumberContainingEqualSetBits(cur))
printBitRepresentation(cur);
}
int main() {
generateAllSubsets((1 << (SIZE-1)) - 1);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment