📌  相关文章
📜  Java番石榴 | isPowerOfTwo(long x) LongMath 类的例子

📅  最后修改于: 2022-05-13 01:54:50.565000             🧑  作者: Mango

Java番石榴 | isPowerOfTwo(long x) LongMath 类的例子

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-