python--Sword offer--16. The integer power of the value

Implement the function double Power(double base, int exponent) to find the exponent power of base. Library functions must not be used, and large numbers need not be considered.

Example 1:

Input: 2.00000, 10
Output: 1024.00000

Example 2:

Input: 2.10000, 3
Output: 9.26100

Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

Example 1:

Input: 2.00000, 10
Output: 1024.00000
Example 2:

Input: 2.10000, 3
Output: 9.26100
Example 3:

Input: 2.00000, -2
Output: 0.25000
Explanation: 2-2 = 1/22 = 1/4 = 0.25

illustrate:

-100.0 < x < 100.0
n is a 32-bit signed integer whose value is in the range [−231, 231 − 1] .

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if x == 0:
            return 0

        if n < 0:
            n = -n
            x = 1/x

        res = 1
        while n != 0:
            if n & 1:
                res *= x
            x *= x
            n >>= 1
        return round(res, 5)


if __name__ == '__main__':
    solution = Solution()
    a = 2.0000
    b = 10
    reslut = solution.myPow(a, b)
    print(reslut)

    a = 2.1000
    b = 3
    reslut = solution.myPow(a, b)
    print(reslut)

    a = 2.0000
    b = -2
    reslut = solution.myPow(a, b)
    print(reslut)


"""
运行结果:
1024.0
9.261
0.25

Process finished with exit code 0
"""

forward from

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324223884&siteId=291194637