當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Guava LongMath isPowerOfTwo(long x)用法及代碼示例


Guava LongMath類的isPowerOfTwo(long x)方法用於檢查數字是否為2的冪。它接受要檢查的數字作為參數,並根據數字是否為2的冪返回布爾值true或false。

用法:

public static boolean isPowerOfTwo(long x)

參數:此方法接受單個參數x,該參數為long類型,將檢查其2的冪。


返回值:此方法返回一個布爾值。如果x代表2的冪,則返回true;如果x不代表2的冪,則返回false。

異常:該方法不會引發任何異常。

注意:這不同於Long.bitCount(x)== 1,因為Long.bitCount(Long.MIN_VALUE)== 1,但Long.MIN_VALUE不是2的冪。

範例1:

// Java code to show implementation of 
// isPowerOfTwo(long x) method of Guava's 
// LongMath class 
  
import java.math.RoundingMode; 
import com.google.common.math.LongMath; 
  
class GFG { 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        long n1 = 52; 
  
        // Using isPowerOfTwo(long x) method 
        // of Guava's LongMath class 
        if (LongMath.isPowerOfTwo(n1)) 
            System.out.println(n1 
                               + " is power of 2"); 
        else
            System.out.println(n1 
                               + " is not power of 2"); 
  
        long n2 = 4; 
  
        // Using isPowerOfTwo(long x) method 
        // of Guava's LongMath class 
        if (LongMath.isPowerOfTwo(n2)) 
            System.out.println(n2 
                               + " is power of 2"); 
        else
            System.out.println(n2 
                               + " is not power of 2"); 
    } 
}
輸出:
52 is not power of 2
4 is power of 2

範例2:

// Java code to show implementation of 
// isPowerOfTwo(long x) method of Guava's 
// LongMath class 
  
import java.math.RoundingMode; 
import com.google.common.math.LongMath; 
  
class GFG { 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        long n1 = 256; 
  
        // Using isPowerOfTwo(long x) method 
        // of Guava's LongMath class 
        if (LongMath.isPowerOfTwo(n1)) 
            System.out.println(n1 
                               + " is power of 2"); 
        else
            System.out.println(n1 
                               + " is not power of 2"); 
  
        long n2 = 4096; 
  
        // Using isPowerOfTwo(long x) method 
        // of Guava's LongMath class 
        if (LongMath.isPowerOfTwo(n2)) 
            System.out.println(n2 
                               + " is power of 2"); 
        else
            System.out.println(n2 
                               + " is not power of 2"); 
    } 
}
輸出:
256 is power of 2
4096 is power of 2

參考: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/LongMath.html#isPowerOfTwo-long-



相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Java Guava | isPowerOfTwo(long x) of LongMath Class with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。