2010-06-20 105 views
4

如果我在Java中有一個整數,除了前導零之外,我怎樣計算有多少位爲零?零位整數,除前導零之外

我們知道Java中的整數有32位,但是計算數字中設置位的數量,然後從32中減去並不會給我我想要的,因爲這還包括前導零。

作爲一個例子,數字5有一個零位,因爲在二進制中它是101

+1

定義 「不正確」。 – Stephen 2010-06-20 15:37:21

+0

我根據發表到我原始答案的評論編輯了問題。 – 2010-06-20 16:21:31

+0

請參閱:http://java.sun.com/javase/6/docs/api/java/lang/Integer.html#bitCount (int) 和http://java.sun.com/javase/6/docs /api/java/lang/Integer.html#numberOfLeadingZeros(int) – laura 2010-06-20 18:09:23

回答

3

要計算非領導在Java中零您可以使用此算法:

public static int countNonleadingZeroBits(int i) 
{ 
    int result = 0; 
    while (i != 0) 
    { 
     if (i & 1 == 0) 
     { 
      result += 1; 
     } 
     i >>>= 1; 
    } 
    return result; 
} 

該算法將是相當快的,如果你的輸入通常很小,但如果你輸入通常是一個較大的數目可能更快地使用this page上的一個bit hack算法的變體。

+0

是的,但給定數字5 // 101這裏是1零而不是30 – 2010-06-20 15:38:22

+1

@ davit-datuashvili:所以你想要統計前導零的零值? – 2010-06-20 15:39:51

+0

'5 = 000 ... 000101'。你想要的是最後一個(最重要的)設置的位的數量加上一個和減去設置的位數。 – ony 2010-06-20 15:41:15

1

計算您的號碼中「位」的總數,然後從總位數中減去1的位數。

1

這就是我會做的。

public static int countBitsSet(int num) { 
    int count = num & 1; // start with the first bit. 
    while((num >>>= 1) != 0) // shift the bits and check there are some left. 
     count += num & 1; // count the next bit if its there. 
    return count; 
} 

public static int countBitsNotSet(int num) { 
    return 32 - countBitsSet(num); 
} 
+0

'32 -x'不是OP想要的。正在計數的位不全是32位,只是最後一位設置位。 (他在原始問題中只是沒有解釋得很好) – Stephen 2010-06-20 16:11:40

-2

由於Java的評估順序是defined,我們可以這樣做:

public static int countZero(int n) { 
    for (int i=1,t=0 ;; i<<=1) { 
     if (n==0) return t; 
     if (n==(n&=~i)) t++; 
    } 
} 

注意,這依賴於平等的LHS第一被評估;在C或C++中嘗試相同的東西,編譯器可以自由設置您的打印機,讓您看起來很愚蠢。

+2

-1對於難以讀取的代碼。 – starblue 2010-06-20 19:12:04

0

使用一些內置的功能:

public static int zeroBits(int i) 
{ 
    if (i == 0) { 
     return 0; 
    } 
    else { 
     int highestBit = (int) (Math.log10(Integer.highestOneBit(i))/
       Math.log10(2)) + 1; 
     return highestBit - Integer.bitCount(i); 
    } 
} 
6

Integer API文檔看看:

32 - Integer.numberOfLeadingZeros(n) - Integer.bitCount(n)