[leetcode]50

采用位运算符,算法复杂度logn
不明白为什么要这么操作
就是不知道这种解法是如何想到的

#include<iostream>
#include <cmath>
#include <iomanip>
using namespace  std;
double myPow(double x, int n) {
    if (n == 0) {//特例
        return 1;
    }

    //处理次数
    unsigned int p = 0;
    if (n < 0) {//负次方
        x = 1 / x;
        p += -n;
    }
    else {
        p = n;
    }

    unsigned int f = 1;
    double out = 1.0;
    double bs = x;

    while (f <= p && f != 0) {
        if (f & p) {
            out *= bs;
        }
        f <<= 1;
        bs *= bs;
    }
    
    return out;
}

int main()
{
    cout << sizeof(unsigned int) << endl;

    cout<<myPow(0.00001, 2147483647)<<endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/tailiang/p/11712394.html