Reverse the bits of a number?
Short answer: public uint ReverseBits(uint n) { uint result = 0; for (int i = 0; i < 32; i++) { result <<= 1; result |= (n & 1); n >>= 1; } return result; } Explanation: Iteratively take least significant bit of n, add it to result’s LSB, shift both accordingly. Follow on: Follow on:
Example code
public uint ReverseBits(uint n) {
uint result = 0;
for (int i = 0; i < 32; i++) {
result <<= 1;
result |= (n & 1);
n >>= 1;
}
return result;
} Explanation: Iteratively take least significant bit of n, add it to result’s LSB, shift both accordingly. Follow on: Follow on:
Real-world example (ShopNest)
In coding rounds, state complexity aloud, write a clear ShopNest-flavored example (orders, carts), then handle edge cases (empty list, null, overflow).
Say this in the interview
- Define — one clear sentence (the short answer above).
- Example — relate it to a project like ShopNest or your real work.
- Trade-off — when you would not use it.
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png