Reverse Bits of Number
C++
Hard
3 views
Problem Description
Reverse the binary representation of a number.
Real Life: Used in network programming, cryptography.
Step-by-Step Logic:
1. Extract each bit from right
2. Add it to result from left
3. Shift original right, shift result left
4. Repeat for all 32 bits
Official Solution
void operator_q14_reverse_bits() {
unsigned int num = 43; // Binary: 00000000000000000000000000101011
unsigned int result = 0;
for(int i = 0; i < 32; i++) {
result = result << 1; // Make space
result = result | (num & 1); // Add last bit of num
num = num >> 1; // Move to next bit
}
cout << "Original number: 43" << endl;
cout << "After reversing bits: " << result << endl;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!