Last active
May 16, 2016 07:53
-
-
Save giwa/090a016ef7a58ea6360eca3932e12e58 to your computer and use it in GitHub Desktop.
Count 1 in bits ref: http://qiita.com/giwa/items/f4517e23570e99742083
This file contains 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
Which means if x = 10101001010100 | |
^ | |
| | |
| | |
| | |
First set bit from the end |
This file contains 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; | |
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; | |
} | |
This file contains 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
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