Ninja technique🥷 to ACE DSA Interviews.
0
, return 1.0
ans = x
ans
with x
.x
and finally return 1/result
.n
is integer
and range of integers is -2,147,483,648 to 2,147,483,647 so if we convert -2,147,483,648 to positive, it will overflow.class Solution {
public:
double myPow(double x, int n)
{
if (n == 0) return 1.0;
double ans = x;
// long long tempN = (n > 0) ? n : -n; // DON'T-int overflow
long long tempN = n;
if(tempN<) tempN = -tempN; // DO
bool neg = (n > 0) ? false : true;
for (int i = 2; i <= tempN; i++) {
ans *= x;
}
if (neg) {
ans = 1.0 / ans;
}
return ans;
}
};
2^5 = 2*(2^4) = 2*(4^2) = 2*16 = 32
class Solution {
public:
double myPow(double x, int n)
{
double ans = 1.0;
long long tempN = n;
if (tempN < 0) tempN = -1 * tempN;
while (tempN) {
if (tempN % 2 == 1) { //odd
ans *= x;
tempN -= 1;
} else { // even
x *= x;
tempN /= 2;
}
}
if (n < 0) ans = 1.0 / ans;
return ans;
}
};
class Solution {
public:
double myPow(double x, int n)
{
if (n < 0) return 1 / x * myPow(1 / x, -(n + 1));
if (n == 0) return 1;
if (n == 2) return x * x;
if (n % 2 == 0)
return myPow(myPow(x, n / 2), 2);
return x * myPow(myPow(x, n / 2), 2);
}
};