给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
1 # -*- coding:utf-8 -*- 2 class Solution: 3 def Power(self, base, exponent): 4 if exponent == 0: 5 return 1 6 if exponent == 1: 7 return base 8 op = False 9 if exponent < 0: 10 op = True 11 exponent = -exponent 12 result = 1 13 if exponent % 2 == 0: 14 result = self.Power(base * base,exponent // 2) 15 else: 16 result = self.Power(base * base,exponent // 2) * base 17 if op: 18 result = 1 / result 19 return result 20 # write code here
leetcode地址,Java版代码:
1 class Solution { 2 public double myPow(double x, int n) { 3 if (n == 0) { 4 return 1; 5 } 6 if (n == 1) { 7 return x; 8 } 9 if(n == -1){ 10 return 1 / x; 11 } 12 13 double half = myPow(x, n / 2); 14 double mod = myPow(x, n % 2); 15 return half * half * mod; 16 } 17 }