檢查兩個數字的二進位制表示形式是否是字謎的 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");
廣告