Sword refers to Offer 16. Numerical integer power (C++) fast power (binary angle)

Insert picture description here
Insert picture description here
Insert picture description here
Note: This question is the same as the 50 questions on the main site: https://leetcode-cn.com/problems/powx-n/

Problem-solving ideas:

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here

class Solution {
    
    
public:
    double myPow(double x, int n) {
    
    
        bool flag = false;
        long long N = n;//赋值n
        if (N == 0) return 1;//0次方
        if (N < 0) flag = true, N = -N;
        double ret = 1;
        for (int i = 0; i < 32; ++i) {
    
    //由于不超过2的32次方减一,故i少于32
            if ((1 << i) & N) ret *= x;//1 << i表示1的二进制左移i位
            //(1 << i) & N求N的二进制中的1
            x = x * x;
        }

        if (flag) return 1.0 / ret;//负次方
        else return ret;//正数次方
    }
};

Complexity analysis:

Time complexity O(log 2 n): The time complexity of dichotomy is logarithmic level.
Space complexity O(1): variables such as res, b take up extra space of constant size.

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114644717