王廷瑋|數位醫療|智慧醫療: 50. Pow(x, n) WFU

2024年7月4日 星期四

50. Pow(x, n)

50. Pow(x, n)


實現 pow(x, n),它計算 x 的 n 次方(即,x^n)。

範例 1:

輸入:x = 2.00000, n = 10 輸出:1024.00000


Python


class Solution:
def myPow(self, x: float, n: int) -> float:
if n == 0:
return 1
if n < 0:
x = 1 / x
n = -n
if n % 2 == 0:
half = self.myPow(x, n // 2)
return half * half
else:
return x * self.myPow(x, n - 1)

# Example usage:
sol = Solution()
print(sol.myPow(2.00000, 10)) # Output: 1024.00000

16.6MB, 33ms


C++


class Solution {
public:
double myPow(double x, int n) {
long long N = n; // Use a long long type to handle negative edge cases safely
if (N < 0) {
x = 1 / x;
N = -N;
}
return powHelper(x, N);
}
private:
double powHelper(double x, long long n) {
if (n == 0) {
return 1;
}
double half = powHelper(x, n / 2);
if (n % 2 == 0) {
return half * half;
} else {
return x * half * half;
}
}
};

// Example usage:
// Solution sol;
// cout << sol.myPow(2.00000, 10); // Output: 1024.00000

8.09MB, 0ms


Javascript


/**
* @param {number} x
* @param {number} n
* @return {number}
*/
var myPow = function(x, n) {
if (n === 0) {
return 1;
}
// Handle negative exponents
if (n < 0) {
x = 1 / x;
n = -n;
}
return powHelper(x, n);
};

function powHelper(x, n) {
if (n === 0) {
return 1;
}
const half = powHelper(x, Math.floor(n / 2));
if (n % 2 === 0) {
return half * half;
} else {
return x * half * half;
}
}

// Example usage:
console.log(myPow(2.00000, 10)); // Output: 1024.00000
console.log(myPow(2.00000, -2)); // Output: 0.25000

48.97MB, 57ms