Guava – LongMath.isPowerOfTwo方法与实例

Guava – LongMath.isPowerOfTwo方法与实例

Guava的LongMath类的isPowerOfTwo(long x)方法是用来检查一个数字是否是2的幂。它接受要检查的数字作为参数,并根据该数字是否为2的幂,返回布尔值true或false。

语法:

public static boolean isPowerOfTwo(long x)

参数: 该方法接受一个长类型的参数x,该参数将被检查为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-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程