![]() |
VOOZH | about |
Given a non-negative integer n, the task is to reverse the bits in its binary representation and return the resulting decimal number. The reversal should consider only the actual binary digits without any leading zeros.
Examples :
Input : 11
Output : 13
Explanation: (11)10 = (1011)2.
After reversing the bits we get: (1101)2 = (13)10.Input : 10
Output : 5
Explanation : (10)10 = (1010)2.
After reversing the bits we get: (0101)2 = (101)2 = (5)10.
Approach:
The idea is to build the reversed number by examining each bit of the input number from right to left, while simultaneously constructing the result from left to right using left shift and right shift operators.
Step by step approach:
13
Time Complexity: O(log n)
Space Complexity: O(1)