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");
}

更新时间: 2019年7月30日

4K+ 次浏览

开启您的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.