LeetCode Problem no. 50
Published in
2 min readMay 2, 2024
Question no. 50. Pow(x, n)
class Solution {
public double myPow(double x, int n) {
long n1 = n;
if(n1 == 1)
return x;
if(n1 == 0 || x == 1)
return 1;
if(x == 0)
return 0;
int b=0;
if(n1 < 0){
b = 1;
n1 *= -1;
}
double a;
a = 1;
while(n1 > 0){
if(n1%2 == 0){
x = x*x;
n1 /= 2;
}
else{
a *= x;
n1--;
}
}
if(b == 1){
a = 1/a;
}
return a;
}
}
class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 1:
return x
if n == 0:
return 1
b = 0
if n < 0:
b = 1
n -= n+n
a = 1
while(n):
if n%2 == 0:
x *= x
n /= 2
else:
a *= x
n -= 1
if b == 1:
a = 1/a
return a
Normal explanation of the code:
Implement pow(x, n), which calculates x
raised to the power n
(i.e., xn
).
In this task, we are instructed to create an efficient pow() function. The code must execute within a specified time frame. In my approach, I’ve employed the standard method, adding a condition: if the exponent becomes even, we can square the base and halve the exponent, thereby reducing the computation time.
Technical explanation of the code:
Special Cases:
- The code first checks for some special cases:
- If
n
is equal to 1, it directly returnsx
. - If
n
is 0 orx
is 1, it returns 1 (since any number raised to the power of 0 is 1). - If
x
is 0, it returns 0 (since 0 raised to any power other than 0 is 0).
Negative Exponents:
- If
n
is negative, the code sets a flagb
to 1 and makesn1
positive by multiplying it by -1. - This step ensures that we handle negative exponents correctly.
Calculation Loop:
- The code initializes a variable
a
to 1. This will store the final result. - It enters a loop while
n1
is greater than 0. - Within the loop:
- If
n1
is even (i.e., divisible by 2), it squares the value ofx
and dividesn1
by 2. - Otherwise (when
n1
is odd), it multipliesa
byx
and decrementsn1
by 1.
For Negative Exponents:
- If the original exponent
n
was negative (indicated byb == 1
), it computes the reciprocal ofa
(i.e.,1/a
).
Return a.