Reverse Number II
Reverse bits of a given 32 bits unsigned integer.
Constraints:
The input must be a binary string of length 32
.
Solution
This function works by iterating through the bits of n
from right to left. In each iteration, it shifts result
to the left to make room for the next bit, and then adds the least significant bit of n
to result. It then shifts n
to the right to process the next bit. This continues until all bits of n
have been processed.
The time complexity of the algorithm is O(1). This is because the number of iterations of the loop is fixed at 32
, regardless of the input.
The space complexity of the algorithm is also O(1), which means it uses a constant amount of space. This is because weโre only using a fixed number of variables and not any data structures that grow with the size of the input. The integer result and the input n are the only variables being used, and their size does not change with different inputs.
Last updated