Problem link - Bit Manipulation - Reverse Bits
Problem Statement
You are given an unsigned 32-bit integer X. Find the integer formed after reversing the 32-bit binary string of X.
Approach
The code implements a method to reverse the binary representation of the input integer n. It does this by iterating through each bit of n from the least significant bit (LSB) to the most significant bit (MSB). In each iteration, it extracts the current LSB using the modulus operator (% 2
), adds it to the result (ans
), and then shifts n to the right by one bit using integer division (n /= 2
). This process is repeated for all 32 bits, effectively constructing the reversed binary integer in ans. Finally, the result is printed for each test case.
Time Complexity
The time complexity of the code is O(1), as the loop always iterates a fixed number of times (32).
Space Complexity
The space complexity of the code is O(1), as it uses a constant amount of space for variables, regardless of the input size.