[LeetCode] 50. Pow(x, n)

Implement pow(x, n).
Thought process:
Shortest problem description! 
Recursively calculate pow(x, n / 2). Base cases:
  1. n = 0, return 1.
  2. n = 1, return x.
  3. n = -1, return 1 / x.

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Solution {
    public double myPow(double x, int n) {
        if (n == 0) {
            return 1;
        }
        if (n == 1) {
            return x;
        }
        if (n == -1) {
            return 1 / x;
        }
        
        if (n % 2 == 0) {
            double half = myPow(x, n / 2);
            return half * half;
        }
        if (n < 0) {
            return myPow(x, n / 2) * myPow(x, n / 2 - 1);
        }
        return myPow(x, n / 2) * myPow(x, n / 2 + 1);
    }
}

Time complexity: O(logn).

Comments

Popular posts from this blog

[LeetCode] 269. Alien Dictionary

[HackerRank] Roads and Libraries

[LeetCode] 631. Design Excel Sum Formula