LeetCode Pow (x, n)
LeetCode-solving Pow (x, n)
Original question
Evaluate the n power of x.
Note:
When n is a negative number, the opposite number is required.
Example:
Input: x = 2, n =-1
Output: 0.5
Input: x = 2.1, n = 2
Output: 4.41
Solutions
The simplest method is to multiply n x numbers directly, but perform (n-1) operations. Now2 ** 8(The power of 2) as an example, we need to perform 7 multiplication, but if(2 ** 2) ** 4->(2 ** 2) ** 2) ** 2Only three multiplications are required for calculation. That is, when n is an odd number, it is directly multiplied by the current x. When the even number is, x is changed to the square of x, and n is divided by 2. In this way, the results can be quickly obtained. When n is a negative number, it must take the reciprocal.
AC Source Code
Class Solution (object): def myPow (self, x, n): "": type x: float: type n: int: rtype: float "flag = 1 if n> = 0 else-1 result = 1 n = abs (n) while n> 0: if n & 1 = 1: result * = x n> = 1 x * = x if flag <0: result = 1/result return resultif _ name _ = "_ main __": assert Solution (). myPow (2,-1) = 0.5 assert Solution (). myPow (2.1, 2) = 4.41