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);
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP