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
.
Constraints:
- The input must be a binary string of length
32
Example 1:
**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**.
Solve¶
Here is what i done:
- Turn number
n
to binary string usingbin(n)
- Padding
0
to get enough 32 bit, by adding(1<<32)
and remove first bit of the stringbin(n)
(And0b
string from the result, which in total is 3 character) - Revert the product string using
[::-1]
- And finally turn the revert binary string back to number using
int(<binary_string>, base=2)
Or just simple adding it bit by bit, using binary manipulation
uint32_t reverseBits(uint32_t n) {
uint32_t r_num = 0;
for (int i = 0; i < 32; i++) {
r_num <<= 1; //r_num = r_num * 2
r_num += (n >> i) & 1; // r_num = r_num + n[32-i]
}
return r_num;
}
Time Submitted | Status | Runtime | Memory | Language |
---|---|---|---|---|
07/17/2023 22:57 | Accepted | 1 ms | 5.4 MB | c |
07/17/2023 22:45 | Accepted | 53 ms | 16.2 MB | python3 |
Last update :
October 13, 2023
Created : August 16, 2023
Created : August 16, 2023