LC190 - Reverse Bits

Problem

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)

Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

Solution

Intuition

Iterate in reverse and multiply each character by 2 to the power of i. The main point of complexity is input handling, which is formatted as an integer in python. Hence, we simply convert it to a string, keeping the leading zeroes with format(n, '032b

def reverseBits(self, n: int) -> int:
	res = 0
	nstr = format(n, '032b')
	for i in range(31, -1, -1):
		res += int(nstr[i], pow(2, i))
	return res

Optimizing

Use fully bitwise operations and eliminate string conversion.

def reverseBits(self, n: int) -> int:
	res = 0
	for i in range(32):
		bit = (n >> i) & 1
		res = res | (bit << (31-i))
	return res

Last updated