LeetCode 0050. Pow(x, n) Solution in Java, Python, C++, JavaScript, Go & Rust | Explanation + Code

CoderIndeed
0
0050. Pow(x, n)

Description

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.
  • Either x is not zero or n > 0.
  • -104 <= xn <= 104

Solutions

Solution 1: Mathematics (Fast Powering)

The core idea of the fast powering algorithm is to decompose the exponent n into the sum of 1s on several binary bits, and then transform the nth power of x into the product of several powers of x.

The time complexity is O(log n), and the space complexity is O(1). Here, n is the exponent.

PythonJavaC++GoTypeScriptRustJavaScriptC#
class Solution: def myPow(self, x: float, n: int) -> float: def qpow(a: float, n: int) -> float: ans = 1 while n: if n & 1: ans *= a a *= a n >>= 1 return ans return qpow(x, n) if n >= 0 else 1 / qpow(x, -n)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !