1. 描述
颠倒给定的 32 位无符号整数的二进制位。
2. 示例
输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000。
输入:11111111111111111111111111111101
输出:10111111111111111111111111111111
解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293,
因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。
提示:
请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 2 中,输入表示有符号整数 -3,输出表示有符号整数 -1073741825。
进阶:
如果多次调用这个函数,你将如何优化你的算法?
3. 分析
反转二进制串,其实本质上和反转字符串没有区别,可以直接将反转字符串的方式方法都用上。(略:递归、反向循环、压栈和出栈等等)
不过这里因为问题的特殊性,可以借助内置类。
包装类 Integer 内封装了直接反转整数二进制串并返回反转后整数的方法
类 | 方法名 | 功能 |
---|---|---|
Integer | static int reverse(int i) | Returns the value obtained by reversing the order of the bits in the two’s complement binary representation of the specified int value. |
4. 代码
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
return Integer.reverse(n);
}
}