Guava IntMath类的floorPowerOfTwo()方法接受一个参数,并返回比该参数中传递的值小2的最大幂。这等效于:checkedPow(2,log2(x,FLOOR))。
用法:
public static int floorPowerOfTwo(int x)
参数:此方法接受单个参数x,它是整数值。
返回值:该方法返回小于或等于x的2的最大幂。
异常:如果x <= 0,则方法floorPowerOfTwo(int x)抛出IllegalArgumentException。
范例1:
// Java code to show implementation
// of floorPowerOfTwo(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 n1 = 10;
// Using floorPowerOfTwo(int x) method
// of Guava's IntMath class
int ans1 = IntMath.floorPowerOfTwo(n1);
System.out.println("Largest power of 2 less "
+ "than or equal to " + n1 + " is:" + ans1);
int n2 = 127;
// Using floorPowerOfTwo(int x) method
// of Guava's IntMath class
int ans2 = IntMath.floorPowerOfTwo(n2);
System.out.println("Largest power of 2 less "
+ "than or equal to " + n2 + " is:" + ans2);
}
}
输出:
Largest power of 2 less than or equal to 10 is:8 Largest power of 2 less than or equal to 127 is:64
范例2:
// Java code to show implementation
// of floorPowerOfTwo(int x) method
// of Guava's IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
static int findFloorPow(int x)
{
try {
// Using floorPowerOfTwo(int x)
// method of Guava's IntMath class
// This should raise "IllegalArgumentException"
// as x <= 0
int ans = IntMath.floorPowerOfTwo(x);
// Return the answer
return ans;
}
catch (Exception e) {
System.out.println(e);
return -1;
}
}
// Driver code
public static void main(String args[])
{
int x = -3;
try {
// Function calling
findFloorPow(x);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
java.lang.IllegalArgumentException:x (-3) must be > 0
相关用法
- Java Guava IntMath mod()用法及代码示例
- Java Guava IntMath mean()用法及代码示例
- Java Guava IntMath gcd(int a, int b)用法及代码示例
- Java Guava IntMath pow(int b, int k)用法及代码示例
- Java Guava IntMath ceilingPowerOfTwo()用法及代码示例
- Java Guava IntMath isPrime()用法及代码示例
- Java Guava IntMath isPowerOfTwo()用法及代码示例
- Java Guava IntMath binomial()用法及代码示例
- Java Guava IntMath sqrt(int x, RoundingMode mode)用法及代码示例
- Java IntMath.checkedSubtract(int a, int b)用法及代码示例
- Java IntMath.checkedAdd(int a, int b)用法及代码示例
- Java IntMath.checkedMultiply(int a, int b)用法及代码示例
- Java IntMath.checkedPow(int b, int k)用法及代码示例
注:本文由纯净天空筛选整理自bansal_rtk_大神的英文原创作品 Java Guava | floorPowerOfTwo() method IntMath Class。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。