Prove safety questions integer power plane 16. offer value

Title Description

Function to achieve double Power (double base, int exponent), seeking base of the exponent power. Not use library functions, while eliminating the need to consider the problem of large numbers.

示例 1:

输入: 2.00000, 10
输出: 1024.00000
示例 2:

输入: 2.10000, 3
输出: 9.26100
示例 3:

输入: 2.00000, -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25

Topic links: https://leetcode-cn.com/problems/shu-zhi-de-zheng-shu-ci-fang-lcof

Simple solution - thinking all cases

class Solution {
public:
    double myPow(double x, int n) {
        if(n == 0 || x == 1.00) return 1.00;

        int flag = 1;
        if(n < 0){
            n = -n;
           flag = 0;
        }

        double rst = 1.00;
        if(flag){
            for(int i = 0 ; i < n;i ++)
                rst *= x;
        }else{
            for(int i = 0; i < n; i++)
                rst /= x;
        }

        return rst;
    }
};

Quick power solution

$$
Since Base = Base ^ * Base 2
$$

$$
basis ^ 2 * 2 = ^ basis basis ^ 4
$$

$$
Similarly * Base. 4 ^ ^ Base = Base. 4. 8 ^
$$

For any non-negative exponent separable into a binary exponential, e.g.
$$
Base Base ^ = ^ {11}. 1 * 2 * Base Base ^ ^. 8
$$
Note: $ [11] {decimal} = [1011] {} binary $

Fast power template code

// int pow(int base,int exp) 
// 快速幂函数,返回 base^exp
// base 底数,exp指数
int pow(int base, int exp){
    int ans = 1;
    while(exp){               
        if(exp & 0x1){
            ans *= base;//如果二进制的最后一位是1,则让ans = ans * base
        }
        
        base *= base;//第一次循环,base=base,第二次base = base^2...
        exp >>= 1;
    }   
    
    return ans;
}

Answer this question

class Solution {
public:
    double myPow(double base, int n) {
        double res = 1.0;
        int exp = n;
        while(exp){
            if(exp & 0x01) res *= base;
            base *= base;
            exp /= 2;
        }
        return n>0?res:1.0/res;
    }
};

Guess you like

Origin www.cnblogs.com/Justdocument/p/12601511.html