数值的整数次方

你快乐吗?

Posted by bbkgl on September 26, 2019

数值的整数次方


C++,实现求幂函数power。下面说下思路:

  1. 如果a>=0:

    • 如果b是偶数:a^b = a^(b/2) x a^(b/2);
    • 如果b是奇数:a^b = a^(b/2) x a^(b/2) x a;
    • 边界条件:a^0 = 1, a^1 = a;
  2. 如果a<0:

    • 如果b是偶数:a^b = a^(b/2) x a^(b/2);
    • 如果b是奇数:a^b = a^(b/2) x a^(b/2) / a;
    • 边界条件:a^0 = 1, a^-1 =1 / a;

代码如下:

class Solution {
public:
    double Power(double base, int exponent) {
        if (exponent == 0) return 1;
        if (exponent == 1) return base;
        if (exponent == -1) return 1 / base;
        if (exponent % 2 == 0) {
            double t = Power(base, exponent / 2);
            return t * t;
        } else {
            double a = Power(base, exponent / 2);
            if (exponent < 0) 
                return a * a / base;
            else return a * a * base;
        }
    }
};