math.ceiling java,Java Guava IntMath ceilingPowerOfTwo()用法及代碼示例

Guava的IntMath類的ceilingPowerOfTwo(int x)方法接受一個參數,並計算出比該參數中傳遞的值大2的最小冪。此方法等效於checkedPow(2,log2(x,CEILING))。

用法:

public static int ceilingPowerOfTwo(int x)

參數:此方法接受單個參數x,該參數為整數類型,並返回比參數中傳遞的值大2的最小冪。

返回值:大於或等於x的2的最小冪。

異常:

IllegalArgumentException:如果x <= 0,則此方法引發IllegalArgumentException。

ArithmeticException:如果next-higher的2的冪不能表示為int,即x> 2^30時,此方法將引發ArithmeticException。

下麵的示例說明IntMath類的ceilingPowerOfTwo()方法:

範例1:

// Java code to show implementation of

// isPrime(int n) 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 isPrime(int n)

// method of Guava's IntMath class

if(IntMath.isPrime(a1))

System.out.println(a1 + " is a prime number");

else

System.out.println(a1 + " is not a prime number");

int a2 = 17;

// Using isPrime(int n)

// method of Guava's IntMath class

if(IntMath.isPrime(a2))

System.out.println(a2 + " is a prime number");

else

System.out.println(a2 + " is not a prime number");

}

}

輸出:

Smallest power of 2 greater than or equal to 25 is:32

Smallest power of 2 greater than or equal to 65 is:128

範例2:

// Java code to show implementation of

// ceilingPowerOfTwo(int x) method of Guava's

// IntMath class

import java.math.RoundingMode;

import com.google.common.math.IntMath;

class GFG {

static int findCeilPow(int x)

{

try {

// Using ceilingPowerOfTwo(int x)

// method of Guava's IntMath class

// This should throw "IllegalArgumentException"

// as x <= 0

int ans = IntMath.ceilingPowerOfTwo(x);

// Return the answer

return ans;

}

catch (Exception e) {

System.out.println(e);

return -1;

}

}

// Driver code

public static void main(String args[])

{

int n = -4;

try {

// Function calling

findCeilPow(n);;

}

catch (Exception e) {

System.out.println(e);

}

}

}

輸出:

java.lang.IllegalArgumentException:x (-4) must be > 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值