Java Guava | floorPowerOfTwo() method IntMath Class
The floorPowerOfTwo() method of Guava’s IntMath class accepts a parameter and returns the largest power of two less than the value passed in the parameter. This is equivalent to: checkedPow(2, log2(x, FLOOR)).
Syntax :
public static int floorPowerOfTwo(int x)
Parameters: This method accepts a single parameter x which is an integral value.
Return Value : The method returns the largest power of two less than or equal to x.
Exceptions : The method floorPowerOfTwo(int x) throws IllegalArgumentException if x <= 0.
Example 1 :
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
public static void main(String args[])
{
int n1 = 10 ;
int ans1 = IntMath.floorPowerOfTwo(n1);
System.out.println( "Largest power of 2 less "
+ "than or equal to " + n1 + " is : " + ans1);
int n2 = 127 ;
int ans2 = IntMath.floorPowerOfTwo(n2);
System.out.println( "Largest power of 2 less "
+ "than or equal to " + n2 + " is : " + ans2);
}
}
|
Output :
Largest power of 2 less than or equal to 10 is : 8
Largest power of 2 less than or equal to 127 is : 64
Example 2 :
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
static int findFloorPow( int x)
{
try {
int ans = IntMath.floorPowerOfTwo(x);
return ans;
}
catch (Exception e) {
System.out.println(e);
return - 1 ;
}
}
public static void main(String args[])
{
int x = - 3 ;
try {
findFloorPow(x);
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output :
java.lang.IllegalArgumentException: x (-3) must be > 0
Reference :
https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#floorPowerOfTwo-int-
Last Updated :
23 Jan, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...