给定一个非负整数 n。目标是反转 n 的位,并报告结果数字。在反转位时,使用整数的实际二进制形式;不考虑前导 0。
让我们看看各种输入输出情况输入 − 13
输出 − 反转给定数字 11 的实际位
(13)10 = (1101)2.after reversing the bits, we get:(1011)2 = (11)10.
explanation − 从输入的数字中获取二进制位,然后将其反转,并最终转换为十进制格式,作为输出返回。
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 number11
以上就是在java中反转给定数字的实际位的详细内容。
   
 
   