Calculating powers of integers

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

    base is the number that you want to power up, n is the power, we return 1 if n is 0, and we return the base if the n is 1, if the conditions are not met, we use the formula base*(powerN(base,n-1)) eg: 2 raised to to using this formula is : 2(base)*2(powerN(base,n-1)).

    public int power(int base, int n){
       return n == 0 ? 1 : (n == 1 ? base : base*(power(base,n-1)));
    }
    

提交回复
热议问题