Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 50 · Math

Pow(x, n)

LeetCode 50 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

Square the base and halve the exponent; peel off one factor when odd.

ಮಧ್ಯಮMathRecursion
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು Pow(x, n) (LeetCode 50) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Math ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Fast exponentiation: x^n = (x²)^(n/2) when n is even, and x · x^(n−1) when it's odd. Halving the exponent each time gives O(log n) multiplications. A negative exponent is just the reciprocal.

Approach

  1. 1

    Work with |n|.

  2. 2

    Odd exponent: multiply ans by x, subtract 1.

  3. 3

    Even exponent: square x, halve the exponent.

  4. 4

    If n was negative, return 1 / ans.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Binary exponentiationPythonO(log n) time · O(1) space
"""
    n=3 -> 3/2, 2^2*2- I need to multiply with current answer with 2 and next time power would be 2
    n = 2 -> x*x, power - 2//2  - 1
    if the power is odd, substract by 1 else take current number and do a multiple with same number
"""
class Solution:
    def myPow(self, x: float, n: int) -> float:
        temp_power=n
        if n<0:
            temp_power=(-1)*n
        ans = 1
        while temp_power>0:
            if temp_power%2==1:
                temp_power=temp_power-1
                ans = ans*x
            else:
                x = (x*x)
                temp_power = temp_power//2
        if n<0:
            return 1/ans
        return ans

ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

Pow(x, n) — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

Pow(x, n) ಹಿಂದಿನ intuition ಏನು?

Fast exponentiation: x^n = (x²)^(n/2) when n is even, and x · x^(n−1) when it's odd. Halving the exponent each time gives O(log n) multiplications. A negative exponent is just the reciprocal.

Pow(x, n) (LeetCode 50) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. Work with |n|. 2. Odd exponent: multiply ans by x, subtract 1. 3. Even exponent: square x, halve the exponent. 4. If n was negative, return 1 / ans.

Pow(x, n) ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(log n). Space: O(1). (Accepted approach: Binary exponentiation.)

Pow(x, n) ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Looping n times is too slow for n ≈ 2³¹.