首页 文章资讯内容详情

在 Java 中反转给定数字的实际位

2026-06-02 1 花语

给定一个非负整数n。目标是反转n的位并报告由此产生的数字。在反转位时,使用整数的实际二进制形式;不考虑前导0。

让我们看看这个的各种输入输出场景

输入 -13

输出 -反转给定数字11的实际位

(13)10 = (1101)2. After reversing the bits, we get: (1011)2 = (11)10.

说明-从输入数字中获得二进制位,然后将其反转并最终转换为十进制格式,作为输出返回。

输入 -18

输出 -反转给定数字9的实际位

(18)10 = (10010)2. After reversing the bits, we get: (1001)2 = (9)10.

说明-从输入数字中获得二进制位,然后将其反转并最终转换为十进制格式,作为输出返回。

下面程序中使用的方法如下

在main方法里面

该数字作为输入并在方法中传递reverseBinaryBits(intinput)

方法里面reverseBinaryBits(intinput)

按位右移操作用于在n的二进制表示中一位一位地取回,按位左移操作用于在rev中累加它们。

变量rev_input被初始化以存储反转位

循环以断点迭代(输入>0)(我们从右侧遍历)

示例

class nhooo{ 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