LeetCode-Solutions-in-Cpp17

Solutions to high-frequency interview questions of LeetCode in C++17, taking into account both efficiency and comprehensibility.


Project maintained by downdemo Hosted on GitHub Pages — Theme by mattgraham
3 ^ 10 = 3 ^ 5 * 3 ^ 5
3 ^ 5 = 3 ^ 2 * 3 ^ 2 * 3
3 ^ 2 = 3 ^ 1 * 3 ^ 1
3 ^ 1 = 3 ^ 0 * 3 ^ 0 * 3
double myPow(double x, int n) {
  if (!n) {
    return 1.0;
  }
  double t = myPow(x, n / 2);
  return n % 2 & 1 ? t * t * x : t * t;
}
class Solution {
 public:
  double myPow(double x, int n) {
    double t = 1;
    if (n < 0) {
      x = 1 / x;
      t = x;
      n = -(n + 1);
    }
    return t * helper(x, n);
  }

  double helper(double x, int n) {
    if (!n) {
      return 1.0;
    }
    double t = helper(x, n / 2);
    return n % 2 & 1 ? t * t * x : t * t;
  }
};