Java程序检查二进制表示是否为回文
回文是指正读反读都一样的序列。检查数字的二进制表示是否为回文,但不考虑前导0。如下例所示:
Number = 5 Binary representation = 101
数字5的二进制表示是回文,因为它正读反读都一样。
演示此功能的程序如下所示。
示例
public class Example {
public static void main(String argc[]) {
long num = 5, n1;
long reverse = 0;
n1 = num;
while (n1 > 0) {
reverse <<= 1;
if ((n1 & 1) == 1)
reverse ^= 1;
n1 >>= 1;
}
if(num == reverse) {
System.out.println("Binary representation of " + num + " is palindrome");
}else {
System.out.println("Binary representation of " + num + " is not palindrome");
}
}
}
输出
Binary representation of 5 is palindrome
现在让我们了解以上程序。
使用while循环获得给定数字5的反转。演示此功能的代码片段如下所示:
long num = 5, n1;
long reverse = 0;
n1 = num;
while (n1 > 0) {
reverse <<= 1;
if ((n1 & 1) == 1)
reverse ^= 1;
n1 >>= 1;
}
如果数字与其反转相同,则它是回文并打印出来,否则它不是回文并打印出来。演示此功能的代码片段如下所示:
if(num == reverse) {
System.out.println("Binary representation of " + num + " is palindrome");
}else {
System.out.println("Binary representation of " + num + " is not palindrome");
}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP