Problem
Problem page: https://leetcode.com/problems/powx-n/
Topics: Math, Binary Search
Difficulty: Medium
Similar problems: (M) Sqrt(x)
Implement pow(x, n).
Analysis
Multiplying n copies of x together is hardly the kind of algorithm that belongs on LeetCode. Here I halve the exponent and use recursion to speed up the calculation.
For example, pow(x, 5) == (x * pow(x, 4)) == (x * pow(pow(x, 2), 2)).
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-pow-x-n/
