Skip to the content.

数值的整数次方


Contact me:

Blog -> https://cugtyt.github.io/blog/index
Email -> cugtyt@qq.com
GitHub -> Cugtyt@GitHub


来自牛客 剑指offer

题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

简单方法:

double Power(double base, int exponent) {
    double result = 1;
    bool flag = exponent < 0;
    exponent = abs(exponent);
    for (auto i = 0; i < exponent; ++i) {
        result *= base;
    }
    if (flag) result = 1 / result;
    return result;
}

快速求解:

double Power(double base, int exponent) {
    bool flag = exp < 0;
    exponent = abs(exponent);
    double ans = 1;
    while (exp > 0) {
        if ((exp & 1) == 1) {
            ans = ans * base;
        }
        exp >>= 1;
        base *= base;
    }
    return flag ? 1 / ans : ans;
}

还可以递归求解:

double Power(double base, int exponent) {
    bool flag = exp < 0;
    exponent = abs(exponent);
    double result = getPower(base, exp);
    return flag ? 1 / result : result;
}

double getPower(double base, int exp) {
    if (exp == 0) {
        return 1;
    }
    if (exp == 1) {
        return base;
    }
    double ans = getPower(base, exp >> 1);
    ans *= ans;
    if ((exp & 1) == 1) {
        ans *= base;
    }
    return ans;
}