Reversed bits
Topic description: Reverse the bits of a given 32-bit unsigned integer.
hint:
- Note that in some languages (like Java) there is no unsigned integer type. In this case, both the input and output will be specified as signed integer types and should not affect your implementation since the internal binary representation of the integer is the same whether it is signed or unsigned.
- In Java, the compiler uses two's complement notation to represent signed integers. So in example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.
For example descriptions, please refer to the official website of LeetCode.
Source: LeetCode
Link: https://leetcode-cn.com/problems/reverse-bits/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.
Solution 1: Binary Operations
Consider n as a binary string of length 32, enumerate each bit of n from the low order to the high order, and add it to the flip result result in reverse order. In the code implementation, n is shifted to the right by one bit for each enumeration, so that the lowest bit of the current n is the bit we want to enumerate. The loop ends when n is 0. Note that in some languages (like Java) there is no unsigned integer type, so a right shift operation on n should use a logical right shift.
Description: Refer to the online problem solution, the original solution is very stupid.
public class LeetCode_190 {
/**
* 二进制运算
* 将 n 视作一个长为 32 的二进制串,从低位往高位枚举 n 的每一位,将其倒序添加到翻转结果 result 中。代码实现中,
* 每枚举一位就将 n 右移一位,这样当前 n 的最低位就是我们要枚举的比特位。当 n 为 0 时即可结束循环。需要注意的是,
* 在某些语言(如 Java)中,没有无符号整数类型,因此对 n 的右移操作应使用逻辑右移。
*
* @param n
* @return
*/
public static int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32 && n != 0; ++i) {
result |= (n & 1) << (31 - i);
n >>>= 1;
}
return result;
}
public static void main(String[] args) {
int n = 43261596;
// 测试用例,二进制表示: 00000010100101000001111010011100
System.out.println(Integer.toBinaryString(n));
// 颠倒后二进制表示: 00111001011110000010100101000000
System.out.println(Integer.toBinaryString(reverseBits(n)));
}
}
[Daily Message] There are cracks in life, and sunlight can shine in. There are ups and downs on the road, and talents become strong.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。