Skip to content

Latest commit

 

History

History
79 lines (55 loc) · 1.45 KB

050Pow.md

File metadata and controls

79 lines (55 loc) · 1.45 KB

Description

Implement pow(x, n), which calculates x raised to the power n (xn).

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2^-2 = 1/2^2 = 1/4 = 0.25

Note:

  • -100.0 < x < 100.0
  • n is a 32-bit signed integer, within the range [−231, 231 − 1]

Tags: Math, Binary Search

思路

题意是让你计算 x^n,如果直接计算肯定会超时,那么我们可以想到可以使用二分法来降低时间复杂度。

class Solution {
    func myPow(_ x: Double, _ n: Int) -> Double {
        if x == 0 {
            return 0
        }
        if n < 0 {
            return helper(1/x, -n)
        }

        return helper(x, n)
    }

    func helper(_ x: Double, _ n: Int) -> Double {
        if n == 0 {
            return 1
        }
        if n == 1 {
            return x
        }
        let d: Double = helper(x, (n >> 1))
        if n % 2 == 0 {
            return d * d
        }

        return d * d * x
    }
}

结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:awesome-swift-leetcode