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
现在让我们了解上面的程序。
给定数字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");
}热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短