java pow int_Java Guava IntMath pow(int b, int k)用法及代码示例

Guava IntMath类的方法pow(int b,int k)将b返回到第k次幂。即使结果溢出,也将等于BigInteger.valueOf(b).pow(k).intValue()。此实现在O(log k)时间中运行。

用法:

public static int pow(int b, int k)

异常:如果k <0,则方法pow(int b,int k)抛出IllegalArgumentException。

范例1:

// Java code to show implementation of

// pow(int b, int k) method of Guava's

// IntMath class

import java.math.RoundingMode;

import com.google.common.math.IntMath;

class GFG {

static int findPow(int b, int k)

{

// Using pow(int b, int k)

// method of Guava's IntMath class

int ans = IntMath.pow(b, k);

// Return the answer

return ans;

}

// Driver code

public static void main(String args[])

{

int b = 4;

int k = 5;

int ans = findPow(b, k);

System.out.println(b + " to the " + k

+ "th power is:"

+ ans);

b = 12;

k = 3;

ans = findPow(b, k);

System.out.println(b + " to the " + k

+ "th power is:"

+ ans);

}

}

输出:

4 to the 5th power is:1024

12 to the 3th power is:1728

范例2:

// Java code to show implementation of

// pow(int b, int k) method of Guava's

// IntMath class

import java.math.RoundingMode;

import com.google.common.math.IntMath;

class GFG {

static int findPow(int b, int k)

{

try {

// Using pow(int b, int k)

// method of Guava's IntMath class

// This should throw "IllegalArgumentException"

// as k < 0

int ans = IntMath.pow(b, k);

// Return the answer

return ans;

}

catch (Exception e) {

System.out.println(e);

return -1;

}

}

// Driver code

public static void main(String args[])

{

int b = 4;

int k = -5;

try {

// Using pow(int b, int k)

// method of Guava's IntMath class

// This should throw "IllegalArgumentException"

// as k < 0

IntMath.pow(b, k);

}

catch (Exception e) {

System.out.println(e);

}

}

}

输出:

java.lang.IllegalArgumentException:exponent (-5) must be >= 0

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值