Implement pow(x, n).
Subscribe to see which companies asked this question
class Solution {
public:
double myPow(double x, int n) {
double ans = 1.0;
double temp = x;
bool flag = false;
long long cnt = n;
if(cnt == 0) return 1.0;
if(cnt < 0) {
flag = true;
cnt = -cnt;
}
while(cnt > 0) {
if(cnt & 1) {
ans *= temp;
}
temp *= temp;
cnt = cnt >> 1;
}
return flag==true?1.0/ans:ans;
}
};