Implement pow(x, n), which calculates x raised to the power n (i.e., xn).
Solution
In our first try, we multiply by iteration ➡ multiply n times
C# Solution
❌First try ➡ Time Limit Exceeded Error
public class Solution {
public double MyPow(double x, int n) {
if(x == 0)
{
return 0.0;
}
else if (n == 0)
{
return 1.0;
}
double res = 1;
bool neg = n < 0;
if(neg)
{
n*=-1;
}
for(int i = 0;i<n;i++)
{
res*=x;
}
//if x is a negative number
if(neg)
{
res = 1/res;
}
return res;
}
}
⭐Solution1
In this solution, as example 28 can write as 2*2*2*2*2*2*2*2
Also can write as 22 * 22 * 22 * 22 or 42 * 42
So if we can get 42 ,we can simplify the multiplication times.
public class Solution {
public double MyPow(double x, int n) {
if(x == 0)
{
return 0.0;
}
double res = cal(x, n);
return n>0 ? res : 1/res;
}
private double cal(double x, int n)
{
//Console.WriteLine("x:"+x+",n="+n); //*1
if (n == 0)
{
return 1.0;
}
double res = cal(x*x,n/2);
return n%2 == 0 ? res : res*x;
}
}
you can see the log with the code at *1
Java Solution
Solution1
class Solution {
public double myPow(double x, int n) {
if(x == 0)
{
return 0.0;
}
double res = cal(x, n);
return n>0 ? res : 1/res;
}
private double cal(double x, int n)
{
if (n == 0)
{
return 1.0;
}
double res = cal(x*x,n/2);
return n%2 == 0 ? res : res*x;
}
}
Python3 Solution
Solution1
def cal(x: float, n: int) -> float:
if n == 0:
return 1.0
res = cal(x*x,(int)(n/2))
return res if n%2 == 0 else res*x
class Solution:
def myPow(self, x: float, n: int) -> float:
if x == 0:
return 0
res = cal(x, n)
return res if n>0 else 1/res
JavaScript Solution
Solution1
/**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function(x, n) {
if(x == 0)
{
return 0.0;
}
res = cal(x, n);
return n>0 ? res : 1/res;
};
function cal(x, n)
{
if (n == 0)
{
return 1.0;
}
res = cal(x*x,parseInt(n/2));
return n%2 == 0 ? res : res*x;
}
Conclusion
🧡If my solution helps, that is my honor!
🧡You can support me by clicking some ad, Thanks a lot
✅If you got any problem about the explanation or you need other programming language solution, please feel free to let me know (either leave a comment or contact me by Messenger is ok!)
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};