实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题
package leecode;
/**
* 功能描述:数值的整数次方
*
* @Author: lwg
* @Date: 2021/4/27 17:20
*/
public class demo17 {
public static double mypow(double x, int n) {
if (x == 0) {
return 0;
}
long b = n;
if (b < 0) {
x = 1 / x;
b = -b;
}
double res = 1.0;
while (b > 0) {
if ((b & 1) == 1) { //幂取余
res = res * x;
}
x *= x; //x=x^2
b >>= 1; //相当于n//=2
}
return res;
}
public static void main(String[] args) {
System.out.println(mypow(3, 5));
}
}