Last active
January 30, 2016 04:46
-
-
Save kartikkukreja/c3df6f4a63faa3e7fa44 to your computer and use it in GitHub Desktop.
Next higher number containing equal set bits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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