50. Pow(x, n)

Pow(x, n)

Pow(x, n)



Implement pow(x, n), which calculates x raised to the power n (i.e., xn).

 

Example 1:

Input: x = 2.00000, n = 10
Output: 1024.00000


Example 2:

Input: x = 2.10000, n = 3
Output: 9.26100


Example 3:

Input: x = 2.00000, n = -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

 

Constraints:

  • -100.0 < x < 100.0
  • -231 <= n <= 231-1
  • n is an integer.
  • -104 <= xn <= 104

Approach) Iterative

var myPow = function(x, n) {
    var ans = 1.0;
    var N = Math.abs(n);
    while(N>0)
    {
        if(N%2===1)
        {
            ans *= x;
        }
        x *= x;
        N = Math.floor(N/2);
    }
    return n<0? 1/ ans : ans;
};


Approach) Recursion

var myPow = function(x, n) {
	function helper(x,n){
		if(n === 0) return 1
		if(x === 0) return 0
		const half = helper(x, Math.floor(n/2))

		if(n % 2 === 1){
			return half * half * x
		}else{
			return half * half
		}
	}

	let result = helper(x,Math.abs(n))

	return result = n >= 0 ? result : 1/result
};

OR

var myPow = function(x, n) {
    if(n === 0)
    {
        return 1;
    }
    if(n<0)
    {
        return myPow(1/x, -n);
    }
    return n % 2 === 0 ? myPow(x*x, n/2) : x* myPow(x*x, Math.floor(n/2)); 
};

Conclusion

That’s all folks! In this post, we solved LeetCode problem 50. Pow(x, n)

I hope you have enjoyed this post. Feel free to share your thoughts on this.

You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.


In this blog, I have tried to collect & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!

Comments

Popular Post