How to write a function that can calculate power in Java. No loops

后端 未结 9 1108
一个人的身影
一个人的身影 2021-01-03 08:28

I\'ve been trying to write a simple function in Java that can calculate a number to the nth power without using loops.
I then found the Math.pow(a, b) class...

9条回答
  •  迷失自我
    2021-01-03 09:21

    A recursive method would be the easiest for this :

    int power(int base, int exp) {
        if (exp != 1) {
            return (base * power(base, exp - 1));
        } else {
            return base;
        }
    }
    

    where base is the number and exp is the exponenet

提交回复
热议问题