Calculating powers of integers

前端 未结 16 2069
情书的邮戳
情书的邮戳 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:45

    There some issues with pow method:

    1. We can replace (y & 1) == 0; with y % 2 == 0
      bitwise operations always are faster.

    Your code always decrements y and performs extra multiplication, including the cases when y is even. It's better to put this part into else clause.

    public static long pow(long x, int y) {
            long result = 1;
            while (y > 0) {
                if ((y & 1) == 0) {
                    x *= x;
                    y >>>= 1;
                } else {
                    result *= x;
                    y--;
                }
            }
            return result;
        }
    

提交回复
热议问题