Pow(x n) LeetCode Solution

Here, We see Pow(x, n) problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

Pow(x, n) LeetCode Solution

Pow(x, n) LeetCode Solution

Problem Statement ->

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

Pow(x n) Leetcode Solution C++ ->

class Solution { public: double myPow(double x, int n) { double res = 1; while (n) { if (n % 2) res = n > 0 ? res * x : res / x; x = x * x; n /= 2; } return res; } };
Code language: C++ (cpp)

Pow(x n) Leetcode Solution Java ->

class Solution { public double myPow(double x, int n) { if(n < 0){ n = -n; x = 1 / x; } double pow = 1; while(n != 0){ if((n & 1) != 0){ pow *= x; } x *= x; n >>>= 1; } return pow; } }
Code language: Java (java)

Pow(x n) Leetcode Solution JavaScript ->

var myPow = function(x, n) { if (n===0) return 1; let pow = Math.abs(n); let result = pow%2===0 ? myPow(x*x,pow/2) : myPow(x*x,(pow-1)/2) * x; return n < 0 ? 1/result : result; };
Code language: JavaScript (javascript)

Pow(x n) Leetcode Solution Python ->

class Solution(object): def myPow(self, x, n): m = abs(n) ans = 1.0 while m: if m & 1: ans *= x x *= x m >>= 1 return ans if n >= 0 else 1 / ans
Code language: Python (python)