Sword refers to Offer 16 (two-point thinking). The integer power of the value

Sword refers to Offer 16 (two-point thinking). The integer power of the value

Problem Description:

Implements pow( x , n ) , a function that computes x raised to the nth power (ie, xn). Library functions must not be used, and there is no need to consider large numbers.

Example:

输入:x = 2.00000, n = 10
输出:1024.00000
输入:x = 2.10000, n = 3
输出:9.26100
输入:x = 2.00000, n = -2
输出:0.25000

Code implementation (the idea is right, but the time limit is exceeded)

class Solution {
    
    
    public double myPow(double x, int n) {
    
    
        if(x == 0.0){
    
    
            return 0.0;
        }
        if(n == 0){
    
    
            return 1.0;
        }
        double number = 1.0;
        if(n < 0){
    
    
            x = 1/x;
            n = -n;
        }
        
        while(n > 0){
    
    
            number = number * x;
            n -= 1;
        }
        return number;
     

    }
}

Problem-solving ideas:Idea link

image-20210830211524976

image-20210830211550440

image-20210830211606908

Code implementation: cut the time in half

class Solution {
    
    
    public double myPow(double x, int n) {
    
    
        if(x == 0.0){
    
    
            return 0.0;
        }
        if(n == 0){
    
    
            return 1.0;
        }
        double number = 1.0;
        //将十进制n转化为二进制b
        long b = n;
        if(b < 0){
    
    
            x = 1/x;
            b = -b;
        }
        while(b > 0){
    
    
            //当b为奇数时,额外乘以x
            if((b & 1)== 1){
    
    
                number *= x;
            }
            x *= x;
            b >>= 1;
        }
        return number;

    }
}

Guess you like

Origin blog.csdn.net/Royalic/article/details/120006158