Leetcode 50. Pow(x, n)

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Pow(x, n)

2. Solution

  • Iterative
class Solution {
public:
    double myPow(double x, int n) {
        double result = 1.0;
        long m = labs(n);
        x = n>0?x:1/x;
        while(m) {
            if(m & 1) {
                result *= x;
            }
            x *= x;
            m >>= 1;
        }
        return result;
    }
};
  • Recursive
class Solution {
public:
    double myPow(double x, int n) {
        x = n>0?x:1/x;
        long m = labs(n);
        return power(x, m);
    }
    
    double power(double x, long n) {
        if(n == 0) {
            return 1;
        }
        if(n % 2) {
            return x * power(x * x, n / 2);
        }
        else {
            return power(x * x, n / 2);
        }
    }
};

Reference

  1. https://leetcode.com/problems/powx-n/description/

推荐阅读更多精彩内容