Skip to content

Instantly share code, notes, and snippets.

@giwa
Last active May 16, 2016 07:53
Show Gist options
  • Save giwa/090a016ef7a58ea6360eca3932e12e58 to your computer and use it in GitHub Desktop.
Save giwa/090a016ef7a58ea6360eca3932e12e58 to your computer and use it in GitHub Desktop.
Which means if x = 10101001010100
^
|
|
|
First set bit from the end
#include<iostream>
#include<bitset>
using namespace std;
int main(){
// 11111 in bits
unsigned int x = 15;
int total = 0;
while (x != 0){
cout << x << endl;
bitset<32> a1(x);
cout << a1 << endl;
bitset<32> a2(x - 1);
cout << a2 << endl;
x = x & (x - 1);
total++;
bitset<32> a3(x);
cout << a3 << endl;
}
cout << total << endl;
}
15
// x
00000000000000000000000000001111
// x - 1
00000000000000000000000000001110
// x & (x - 1)
00000000000000000000000000001110
14
// x
00000000000000000000000000001110
// x - 1
00000000000000000000000000001101
// x & (x -1)
00000000000000000000000000001100
12
// x
00000000000000000000000000001100
// x - 1
00000000000000000000000000001011
// x & (x - 1)
00000000000000000000000000001000
8
// x
00000000000000000000000000001000
// x - 1
00000000000000000000000000000111
// x & (x - 1)
00000000000000000000000000000000
4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment