当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Guava IntMath isPowerOfTwo()用法及代码示例


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

用法:

public static boolean isPowerOfTwo(int x)

参数:此方法接受单个参数x,该参数为整数类型。


返回值:如果x代表2的幂,则该方法返回true;如果x代表2的幂,则该方法返回false。

异常:该方法没有任何异常。

注意:这与Integer.bitCount(x)== 1不同,因为Integer.bitCount(Integer.MIN_VALUE)== 1,但Integer.MIN_VALUE不是2的幂。

范例1:

// Java code to show implementation of 
// isPowerOfTwo(int x) method of Guava's 
// IntMath class 
import java.math.RoundingMode; 
import com.google.common.math.IntMath; 
  
class GFG { 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        int a1 = 63; 
  
        // Using isPowerOfTwo(int x) method 
        // of Guava's IntMath class 
        if (IntMath.isPowerOfTwo(a1)) 
            System.out.println(a1 + " is power of 2"); 
        else
            System.out.println(a1 + " is not power of 2"); 
  
        int a2 = 1024; 
  
        // Using isPowerOfTwo(int x) method 
        // of Guava's IntMath class 
        if (IntMath.isPowerOfTwo(a2)) 
            System.out.println(a2 + " is power of 2"); 
        else
            System.out.println(a2 + " is not power of 2"); 
    } 
}

输出:

63 is not power of 2
1024 is power of 2

范例2:

// Java code to show implementation of 
// isPowerOfTwo(int x) method of Guava's 
// IntMath class 
import java.math.RoundingMode; 
import com.google.common.math.IntMath; 
  
class GFG { 
  
    // Driver code 
    public static void main(String args[]) 
    { 
        int a1 = 10; 
  
        // Using isPowerOfTwo(int x) method 
        // of Guava's IntMath class 
        if (IntMath.isPowerOfTwo(a1)) 
            System.out.println(a1 + " is power of 2"); 
        else
            System.out.println(a1 + " is not power of 2"); 
  
        int a2 = 256; 
  
        // Using isPowerOfTwo(int x) method 
        // of Guava's IntMath class 
        if (IntMath.isPowerOfTwo(a2)) 
            System.out.println(a2 + " is power of 2"); 
        else
            System.out.println(a2 + " is not power of 2"); 
    } 
}

输出:

10 is not power of 2
256 is power of 2

参考:
https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#isPowerOfTwo-int-



相关用法


注:本文由纯净天空筛选整理自bansal_rtk_大神的英文原创作品 Java Guava | isPowerOfTwo() method IntMath Class。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。