标签:
题目来源
https://leetcode.com/problems/powx-n/
Implement pow(x, n).
题意分析
Input: x,n
Output:pow(x,n)
Conditions:满足一定的内存需求,算法复杂度低一些
题目思路
刚开始以为直接乘就好了,但是爆内存了,仔细看发现其实可以通过二分法利用每次乘的信息,注意到n可以为负数,所以预处理为正数先
AC代码(Python)
1 class Solution(object): 2 def myPow(self, x, n): 3 """ 4 :type x: float 5 :type n: int 6 :rtype: float 7 """ 8 def p(x, n): 9 10 if n ==0: 11 return 1.0 12 half = self.myPow(x, n / 2) 13 if n % 2 == 0: 14 return half * half 15 else: 16 return half * half * x 17 s = False 18 if n < 0: 19 n = -n 20 s = True 21 if s == True: 22 return (1.0) / p(x, n) 23 else: 24 return p(x, n) 25 26
[LeetCode]题解(python):050-Pow(x, n)
标签:
原文地址:http://www.cnblogs.com/loadofleaf/p/5071389.html