Last updated on October 10th, 2024 at 02:13 am
Here, We see Pow(x n) LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.
List of all LeetCode Solution
Topics
Math, Recursion
Companies
Bloomberg, Facebook, Google, Linkedin
Level of Question
Medium
Pow(x n) LeetCode Solution
Table of Contents
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
1. 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; } };
2. 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; } }
3. 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; };
4. 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