簡體   English   中英

如何在 Java 中的 integer 中找到 2 的指數?

[英]How to find the exponent of 2 in an integer in Java?

我想找到任何 integer 包含的 2 的冪。 12 = 2*2*3所以答案應該是228 = 2*2*7所以答案應該是2等等。

int powerOf2InNumber = (int)Math.floor(Math.log(number) / Math.log(2));

我嘗試了上面的代碼,但在 28、26、10 等情況下,我得到了錯誤的答案。

有一個方便的內置 function,

int powersOf2 = Integer.numberOfTrailingZeros(number);

這應該可以解決問題:

int check = 28;
int count = 0;
while(check % 2 == 0) {
    check /= 2;
    count++;
}

檢查最終成為另一個因素。 即 2 * 2 * 7 中的 7。計數是您的答案。

我想你要問的是:2 變成數字的次數?

int countPowerOfTwo(int number) {
  int count = 0;
  while (abs(number) > 0) {
    if (number % 2 != 0) {
      return count;
    }
    count++;
    number = number / 2;
  }
  return count;
} 

最好的方式,imo,已經使用Integer.numberOfTrailingZeros提供。 它取自Hacker's Delight ,這是一本很棒的書,物有所值。 另一種方法如下:

int b = 32*75;
int powerOf2 = BitSet.valueOf(new long[]{b}).nextSetBit(0);
System.out.println(powerOf2);

印刷

5

注意:為了完整起見,您的嘗試並不遙遠,對數可以與一些基本的位操作一起使用。 因此,您可以執行以下操作:

int number = 32*75;
int powerOf2 = (int)(Math.log(number & -number)/Math.log(2))

暫無
暫無

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

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