Java程序反转正整数的位
整数的位可以取反以获得另一个数字。一个例子如下:
Number = 11 Binary representation = 1011 Reversed binary representation = 1101 Reversed number = 13
演示此的程序如下所示-
示例
public class Example {
public static void main(String[] args) {
int num = 14;
int n = num;
int rev = 0;
while (num > 0) {
rev <<= 1;
if ((int)(num & 1) == 1)
rev ^= 1;
num >>= 1;
}
System.out.println("The original number is: " + n);
System.out.println("The number with reversed bits is: " + rev);
}
}输出结果
The original number is: 14 The number with reversed bits is: 7
现在让我们了解上面的程序。
编号已定义。然后使用while循环来反转数字的位。证明这一点的代码片段如下所示-
int num = 14;
int n = num;
int rev = 0;
while (num > 0) {
rev <<= 1;
if ((int)(num & 1) == 1)
rev ^= 1;
num >>= 1;
}最后,显示数字以及反向数字。证明这一点的代码片段如下所示-
System.out.println("The original number is: " + n);
System.out.println("The number with reversed bits is: " + rev);热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练