时间复杂度O(logn),空间复杂度O(1)求一个数double x的n次幂
程序员文章站
2024-03-15 22:48:30
...
#include <iostream>
using namespace std;
double f(double x, int n);
int main(){
cout<<f(3, 6)<<endl;
return 0;
}
double f(double x, int n){
double res = 1;
while (n != 0) {
if(n & 1) res *= x;
x *= x;
n = n >> 1;
}
return res;
}