2015-11-02 51 views
2

我已經試過幾乎所有的資源設置爲1的位數回報,我能找到的數字的二進制表示A * B

but i could not solve this ("return the number of bits set to 1 in the binary representation of the number A*B" 

我的問題是,用來計算有多少數據結構1是他們的二進制a * b,編程式

+0

嘗試使用'for'循環和['charAt'](http://docs.oracle.com/javase/8/docs/api/java/lang/String.html# charAt-int-)方法。我認爲這足以提示。當然,只要我輸入這個,別人決定只是給你答案,而不是讓你弄清楚........ :(: – ajb

回答

1

您的結果是在一個字符串中。你可以簡單地遍歷字符並計算它們。

int count = 0; 
for (int i=0;i<str.length;i++){ 
    if (str.charAt(i)=='1'){ 
     count++; 
    } 
} 
-1

下面的代碼應該找到該產品的二進制表示1點的數量:

public static int getNumberOfOnes(int a, int b) { 
    int total = a * b; 
    String binaryString = Integer.toBinaryString(total); 
    return binaryString.split("1").length - 1; 
} 
+0

「split」的javadoc說「尾隨空串是因此沒有包含在結果數組中「基於此,我不認爲這個答案在任何情況下都能正常工作 – ajb

+0

感謝你的回覆隊友 – Nav

2

感嘆,這麼多的答案,使用效率低下的字符串操作...

試試這個:

public static int getNumberOfOnes(int a, int b) { 
    long total = a * b; // 'long' to avoid integer overflow 
    int count = 0; 
    while (total != 0) { 
     if ((total & 1) == 1) ++count; 
     total = total >>> 1; 
    } 
    return total; 
} 
+0

@NavjotVirk這個答案是正確的,它只計算設置爲1的位,如果'語句使用位掩碼和測試來確定值是否以1結尾,那麼它將整個數字右移一位。 – 2015-11-02 03:46:42

+0

@Snowman當然比將數字轉換爲字符串更有效然後計算「1」字符:) – Alnitak

相關問題