50. Pow(x, n)

題目描述

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

解答

Javascript

function myPow(x, n) { let result = 1; while (n) { if (n % 2) { if (n > 0) { result *= x; } else { result /= x; } } x = x * x; n = ~~(n / 2); } return result; }

MarsgoatJul 24, 2023

C++

class Solution { public: double myPow(double base, int n) { long long exponent = (long long) n; if (exponent == 0) { return 1; } if (exponent < 0) { base = 1 / base; exponent = -exponent; } double ans = 1; while (exponent > 0) { if (exponent % 2 == 1) { ans *= base; exponent -= 1; } base = base * base; exponent /= 2; } return ans; } template<typename T> void printVector(const vector<T>& vec) { for (const T& element : vec) { cout << element << ","; } cout << endl; } };

Jerry Wu24 July, 2023

Reference

回到題目列表