簡體   English   中英

count java中的1位數

[英]count Number of 1 Bits in java

我在做一個leetcode問題時遇到了一個奇怪的問題。 這是關於Java中的位表示。

編寫一個取無符號整數的函數,並返回它所具有的“1”位數(也稱為漢明權重)。

例如,32位整數'11'具有二進制表示00000000000000000000000000001011,因此該函數應返回3。

我的解決方案是

public class Solution {
// you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        for(int i = 0; i < 32; ++i){
            if((n >>> i) % 2 == 1){
                ++count;
            }
        }
        return count;
    }
}

由於輸入大小寫,因此不接受此代碼:

4294967295(11111111111111111111111111111111)

我在java中查看了整數的位表示但是仍然不知道解決方案的問題? 誰能幫助我?

當你想要一個按位&時,問題是執行模數。 就像是,

public static int hammingWeight(int n) {
    int count = 0;
    for (int i = 0; i < 32; ++i) {
        if (((n >>> i) & 1) == 1) {
            ++count;
        }
    }
    return count;
}

public static void main(String[] args) {
    int c = -1;
    System.out.println(hammingWeight(c));
}

產出(如預期)

32
public int hammingWeight(int n) {
    return Integer.bitCount(n);
}

Integer.bitCount(int i)

返回指定int值的二進制補碼表示形式中的一位數。

Java使用了兩個贊美。 所以負位是最左邊的位。 這意味着如果您的數字大於Integer.MAX_VALUE您的輸入將為負數。 當您執行%2 ,符號保持不變。 另一種方法是使用&1來改變符號位。 在第一次迭代之后,您已經完成了一次移位,符號位將為零。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM