Solution:read
#include <iostream>
using namespace std;
/**
******************************************************************************
*
* Counting set bits in a 32-bit number
*
* @param v
*
* @return unsigned int
*
******************************************************************************
*/
unsigned int CountBits(unsigned int v)
{
v = v - ((v >> 1) & 0x55555555); // reuse input as temporary
v = (v & 0x33333333) + ((v >> 2) & 0x33333333); // temp
return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24; // count
}
/**
******************************************************************************
*
* Count number of set bits in a 32 bit number.
*
* Reference: http://graphics.stanford.edu/~seander/bithacks.html
*
* @return int
*
******************************************************************************
*/
int main(int argc, char *argv[])
{
unsigned int val;
cout << "Please enter a hex number\n:";
cin >> hex >> val;
cout << hex << CountBits(val) << " bits are set in " << val << endl;
return 0;
}
// This solution is kindly provided by Jeff Fore.
hide solution
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.