I came through an interview question. Reverse bits of a 32 bit unsigned integer. I wrote this code which is completely okay:
uint32_t reverseBits(uint32_t n) {
for(int i = 0, j = 31; i < j; i++, j--) {
bool iSet = (bool)(n & (1 << i));
bool jSet = (bool)(n & (1 << j));
n &= ~(1 << j);
n &= ~(1 << i);
if(iSet) n |= (1 << j);
if(jSet) n |= (1 << i);
}
return n;
}
After this, there was a follow up question - If this function is called many times, how would you optimize it? I can not figure out how the solution should be optimized in that scenario.