The sword refers to the offer – the integer power of the value (super detailed explanation)

Problem Solving: Integer Power of Numbers

Topic description

Topic link:

Thought analysis

  • I just finished reading the question, I thought this question was not difficult, so I fell directly into the pit of the question
    But the above way of writing is not comprehensive for the data. What if the exponent is 0 or a negative number? The above code only considers the case where the exponent is greater than 0

  • If the exponent is negative, we can take an absolute value and return the inverse, then0How to do it? right0It is meaningless to take the reciprocal, and the base is0, but the index is negative, if no processing is done at this time, the program will report an error

  • Here we introduce afast powerThe concept of (from Lc problem solution)

  • Professional Edition

  • simple to understand

  • why uselonglong, if when n is negative infinity, it will exceed the range of int


class Solution {
    double myPow(double x, int n) 
        typedef long long LL;
        bool is_minus = n < 0;
        double res = 1;
        for (LL k = abs(LL(n)); k; k >>= 1) 
            if (k & 1) res *= x;
            x *= x;
        if (is_minus) res = 1 / res;
        return res;

Leave a Comment

Your email address will not be published. Required fields are marked *