题目内容
Reverse bits of a given 32 bits unsigned integer.
Example:
Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100
represents the unsigned integer 43261596,
so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101
represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is
10111111111111111111111111111111.
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 signed integer type and
should not affect your implementation, as the internal binary representation of
the integer 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.
分析过程
- 题目归类:
2进制 - 题目分析:
对于2进制需要了解补码反码左移右移逻辑右移和算术右移等操作。
todo 各种码分析 - 边界分析:
- 空值分析
- 循环边界分析
需要了解到java中int是32位的所以转化成2进制应该是32位。
- 方法分析:
原数&1可以得到最后一位。然后把最后一位写到ref中。在对ref左移,对原数右移。- 数据结构分析
int 32 位 - 状态机
- 状态转移方程
- 最优解
- 数据结构分析
- 测试用例构建
代码实现
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int ref=0;
for(int i = 0; i < 32; i++) {
int end = n&1;
n>>=1;
ref <<=1;
ref |=end;
}
return ref;
}
}
效率提高
拓展问题
Number of 1 Bits