190. Reverse Bits
Bit Manipulation, Divide and Conquer ·Problem Statement
link: https://leetcode.com/problems/reverse-bits/ https://leetcode.cn/problems/reverse-bits/
Reverse bits of a given 32 bits unsigned integer.
Note:
Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer’s internal binary representation is the same, whether it is signed or unsigned. In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.
Example:
Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)
Solution Approach
The solution involves bit manipulation to reverse the individual bits of the given number.
Algorithm
- Initialization: Begin by initializing a result variable to 0 and a power variable to 31, which is the highest bit index for a 32-bit integer.
- Bitwise Manipulation: Using a loop, for each bit of the given number n, check its least significant bit, shift it to its appropriate position in the result by using the current value of power, and add it to the result.
- Shift and Decrease: Right-shift the given number n to move on to the next bit and decrement the power variable. Continue this process until all bits of n are processed.
Implement
class Solution:
def reverseBits(self, n: int) -> int:
res, power = 0, 31
while n:
res += (n & 1) << power
n >>= 1
power -= 1
return res