Calculating powers of integers

前端 未结 16 2028
情书的邮戳
情书的邮戳 2020-12-08 06:18

Is there any other way in Java to calculate a power of an integer?

I use Math.pow(a, b) now, but it returns a double, and that is usually a

16条回答
  •  爱一瞬间的悲伤
    2020-12-08 06:30

    No, there is not something as short as a**b

    Here is a simple loop, if you want to avoid doubles:

    long result = 1;
    for (int i = 1; i <= b; i++) {
       result *= a;
    }
    

    If you want to use pow and convert the result in to integer, cast the result as follows:

    int result = (int)Math.pow(a, b);
    

提交回复
热议问题