
给定一个非负整数 n。目标是反转 n 的位,并报告结果数字。在反转位时,使用整数的实际二进制形式;不考虑前导 0。
让我们看看各种输入输出情况
输入 − 13
输出 − 反转给定数字 11 的实际位
(13)10 = (1101)2. After reversing the bits, we get: (1011)2 = (11)10.
Explanation − 从输入的数字中获取二进制位,然后将其反转,并最终转换为十进制格式,作为输出返回。
立即学习“Java免费学习笔记(深入)”;
Input − 18
Output − 反转给定数字9的实际位。
(18)10 = (10010)2. After reversing the bits, we get: (1001)2 = (9)10.
Explanation − 二进制位从输入数字中获取,然后被反转并最终转换为十进制格式,作为输出返回。
下面程序中使用的方法如下
-
在主方法内部
输入数字并传递给方法 reverseBinaryBits(int input)
-
在方法 reverseBinaryBits(int input) 内部
初始化变量 rev_input 以存储反转的位
-
循环迭代,直到输入大于0(我们从右边开始遍历)
使用位右移操作来逐位检索n的二进制表示中的每一位,并使用位左移操作来累积它们到 rev 中
示例
class TutorialsPoint{
public static int reverseBinaryBits(int input){
int rev_input = 0;
while (input > 0){
rev_input <<= 1;
if ((int) (input & 1) == 1){
rev_input ^= 1;
}
input >>= 1;
}
return rev_input;
}
public static void main(String[] args){
int input = 13;
System.out.println("Reverse actual bits of the given number");
System.out.println(reverseBinaryBits(input));
}
}输出
如果我们运行上面的代码,它将生成以下输出
Reverse actual bits of the given number 11











