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.
Input: n =00000010100101000001111010011100Output: 964176192(00111001011110000010100101000000)Explanation: The input binary string **00000010100101000001111010011100** represents the unsigned integer 43261596, so return964176192 which its binary representation is**00111001011110000010100101000000**.
Example 2:
1
2
3
Input: n =11111111111111111111111111111101Output: 3221225471(10111111111111111111111111111111)Explanation: The input binary string **11111111111111111111111111111101** represents the unsigned integer 4294967293, so return3221225471 which its binary representation is**10111111111111111111111111111111**.
publicclassSolution {
publicintreverseBits(int n) {
int ans = 0;
for (int i = 0; i < 32; i++) {
int bit = (n >> i) & 1;
ans |= (bit << (31 - i));
}
return ans;
}
}
1
2
3
4
5
6
7
classSolution:
defreverseBits(self, n: int) -> int:
ans =0for i in range(32):
bit = (n >> i) &1# Extract the bit at position i ans |= (bit << (31- i)) # Place it at the reversed positionreturn ans
Reverse the bits by swapping bit-blocks of increasing granularity: first swap every pair of bits, then swap 2-bit groups, then 4-bit groups, and so on. Using constant masks and shifts does a fixed number of operations (log2(word_size) steps) and runs in constant time for fixed-width integers.