|
-
April 11th, 2009, 11:45 PM
#3
Re: Some bitwise problems..
I don't believe there is an O(1) solution, but there is an O(number of ones) algorithm involving repeatedly eliminating the least significant bit:
Code:
short int oneBits(short int n) {
short int total;
if (!n) return 0;
for (total = 1; n ^= ((n - 1) ^ n) & n; ++total);
return total;
}
To break it down, it works like this:
- let n = 010111010b
- n - 1 = 010111001 // subtract 1 to change all the bits up to the bit we're interested in
- (n - 1) ^ n = 000000011 // XOR it with the original value to get only the changed bits (those up to and including the interesting bit)
- ((n - 1) ^ n) & n = 0000000010 // AND that with the original value to set only the interesting bit
- n ^ (((n - 1) ^ n) & n) = 010111000 // XOR that with the original value to flip the interesting bit
- if the new value of n is 0, we have no more 1 bits left, so exit
Edit: ah! There's a simpler algorithm to do the same thing in the top link in the post above (by ahoodin). Silly that I didn't see that *learns*
Last edited by Twey; April 11th, 2009 at 11:48 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|