leetcode Pow(x, n)
实现 pow(x, n) ,即计算 x 的 n 次幂函数。
说明:
- -100.0 < x < 100.0
- n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
快速幂
1 class Solution { 2 public: 3 double myPow(double x, int n) { 4 long long N = n; 5 double res = 1; 6 if (N < 0) 7 { 8 N = -N; 9 x = 1.0 / x; 10 } 11 while (N) 12 { 13 if (N & 1) 14 res = res * x; 15 x = x * x; 16 N >>= 1; 17 } 18 return res; 19 } 20 };
递归
1 class Solution { 2 public: 3 double quickpow(double x, long long N){ 4 if(N == 0) return 1; 5 double ans = quickpow(x, N/2); 6 return N & 1 ? ans * ans * x : ans * ans; 7 } 8 double myPow(double x, int n) { 9 long long N = n; 10 return N < 0 ? quickpow(1/x, -N) : quickpow(x,N); 11 } 12 };

浙公网安备 33010602011771号