检查两个数字的二进制表示形式是否是字谜的 Java 程序
如果两个数字的二进制表示形式具有相同数量的 0 和 1,则它们是字谜。如下所示提供了一个示例 -
Number 1 = 3 Binary representation of Number 1 = 0011 Number 2 = 12 Binary representation of Number 2 = 1100
这两个数字是字谜。
一个展示这一点的程序如下 -
示例
public class Example { public static void main (String[] args) { long x = 12, y = 3; if(Long.bitCount(x) == Long.bitCount(y)) System.out.println("Binary representations of " + x + " and " + y + " are anagrams"); else System.out.println("Binary representations of " + x + " and " + y + " are not anagrams"); } }
上述程序的输出如下 -
Binary representations of 12 and 3 are anagrams
现在让我们理解一下上述程序。
定义了 x 和 y 的值。然后计算位表示形式中的 1。如果它们相等,则 x 和 y 的二进制表示形式是字谜,否则不是。展示这一点的代码片段如下 -
long x = 12, y = 3; if(Long.bitCount(x) == Long.bitCount(y)) System.out.println("Binary representations of " + x + " and " + y + " are anagrams"); else System.out.println("Binary representations of " + x + " and " + y + " are not anagrams");
广告