Skip to content

Latest commit

 

History

History
104 lines (76 loc) · 1.96 KB

_50. Pow(x, n).md

File metadata and controls

104 lines (76 loc) · 1.96 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 23, 2024

Last updated : June 23, 2024


Related Topics : Math, Recursion

Acceptance Rate : 36.17 %


Solutions

C

double myPowLong(double x, long n) {
    if (n == 0) 
        return 1.;

    if (n < 0)
        return 1 / myPowLong(x, n * -1);
    
    if (n == 1)
        return x;

    double half = myPowLong(x, n / 2);
    long remainder = n % 2;

    if (remainder == 1)
        return half * half * x;
    return half * half;
}

double myPow(double x, int n) {
    return myPowLong(x, (long) n);
}

Java

class Solution {
    public double myPow(double x, int n) {
        return myPow(x, (long) n);

    }
    private double myPow(double x, long n) {
        if (n == 0) 
            return 1.;

        if (n < 0)
            return 1 / myPow(x, n * -1);
        
        if (n == 1)
            return x;

        double half = myPow(x, n / 2);
        long remainder = n % 2;

        if (remainder == 1)
            return half * half * x;
        return half * half;
    }
}

Python

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if not n :
            return 1
        
        if n == 1 :
            return x
        
        if n < 0 :
            return 1 / self.myPow(x, -n)

        half = n // 2
        remainder = n - half * 2
        half = self.myPow(x, half)

        if remainder :
            return x * half * half
        
        return half * half