回文是向前和向后都相同的序列。检查数字的二进制表示形式是回文,但不考虑前导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
现在让我们了解上面的程序。
给定数字5的倒数是使用while循环获得的。证明这一点的代码片段如下-
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");
}