leetcode 50. Pow(x, n) (x to the nth power)

insert image description here
Find x raised to the nth power.

Ideas:

The first idea that comes to mind is to multiply x and itself n times,
but this will face some problems:
if it is a simple case where n is small, it is fine, but you can see that the value of n spans the entire integer range,
if n is very large, one of which is the inefficiency of multiplying x one at a time.

Generally speaking, if n is a negative number, you will first take abs(n), multiply x until n=0, and then use 1.0/res.
But you will find that if n = -2 31 , then abs(n) will overflow ( Positive numbers range to -2 31 -1), and get wrong results.

So change your mind.

I saw this method on the Internet is good, the time complexity is O(nlogn),
and x n is equivalent to x 2 * x n/2 , so that n is continuously decomposed into n/2. It
is equivalent to recursively calling the myPow function, myPow(x, n) = x 2 * myPow(x, n/2).

But you will ask what to do if n is not divisible by 2,
then take out the remainder and multiply it again: x n = x 2 * x n/2 * x n%2

If n is a negative number,
do it when recursing to n=1 or -1, because when n is negative, you only need to do 1.0/res for the last time. When
n=1, it is x itself, and when n=-1 , which is 1.0/x

public double myPow(double x, int n) {
    
    
    if(n == 0 || x == 1) return 1.0;
    int nMod2 = n % 2;
    double a = 1.0;

   if(nMod2 == 1) {
    
    
        a = x;
    } else if(nMod2 == -1){
    
    
        a = 1.0/x;
    }
    return myPow(x*x, n/2)*a;
}

Guess you like

Origin blog.csdn.net/level_code/article/details/131900120