【力扣】面试题16. 数值的整数次方

题意理解

计算一个数的整数次方,提供的有益帮助是结果不会超过范围,限制条件是不能用库函数

问题分析

考虑负数,0的情况,考虑效率,复杂度o(n)是不行的,需要改成o(lgn)。

其他

https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof/solution/c-cheng-fa-kuai-su-mi-by-yizhe-shi/

链接

class Solution {
public:
    double myPow(double x, int n) {
        if (x == 0.0 && n < 0) {
            return 0;
        }
        long num = n;  //防止出现负数转正数越界的错误。
        bool minusflag = 0;
        if (n < 0) {
            minusflag = 1;
            num = -num;   //不能直接从int转到负数long,需要int转成long,从long转到负数long
        }
        double pow = 1.0;
        while (num) {
            if (num & 1) pow *= x;
            x *= x;    //不是逐个乘一个数,而是对折乘
            num >>= 1;
            //cout << "n " << n << endl;
        }
        if (minusflag == 1) {
            pow = 1.0 / pow;
        }
        return pow;
    }
};

 

你可能感兴趣的:(【力扣】面试题16. 数值的整数次方)