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
相关用法
- Java Guava LongMath binomial(int n, int k)用法及代码示例
- Java Guava LongMath pow(long b, int k)用法及代码示例
- Java Guava LongMath sqrt(long x, RoundingMode mode)用法及代码示例
- Java Guava LongMath gcd(long a, long b)用法及代码示例
- Java Guava LongMath mean(long x, long y)用法及代码示例
- Java Guava LongMath mod(long x, long m)用法及代码示例
- Java LongMath.checkedMultiply(int a, int b)用法及代码示例
- Java LongMath.checkedPow(long b, int k)用法及代码示例
- Java LongMath log10(long x, RoundingMode mode)用法及代码示例
- Java LongMath.divide(long, long, RoundingMode)用法及代码示例
- Java LongMath.checkedAdd(long a, long b)用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Java Guava | isPowerOfTwo(long x) of LongMath Class with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。