Calculating powers of integers

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

    Use the below logic to calculate the n power of a.

    Normally if we want to calculate n power of a. We will multiply 'a' by n number of times.Time complexity of this approach will be O(n) Split the power n by 2, calculate Exponentattion = multiply 'a' till n/2 only. Double the value. Now the Time Complexity is reduced to O(n/2).

    public  int calculatePower1(int a, int b) {
        if (b == 0) {
            return 1;
        }
    
        int val = (b % 2 == 0) ? (b / 2) : (b - 1) / 2;
    
        int temp = 1;
        for (int i = 1; i <= val; i++) {
            temp *= a;
        }
    
        if (b % 2 == 0) {
            return temp * temp;
        } else {
            return a * temp * temp;
        }
    }
    

提交回复
热议问题