要求
Implement pow(x, n)
解
1. 特例
2. 优化
index = (n > 0 ? n : -n); pow(x, index) = (index %2==1 ? pow(x, index/2)*x : pow(x, index/2));
继续优化
pow(x, index) = (index %2==1 ? pow(x, index>>1)*x : pow(x, index>>1));
3. 参考代码
class Solution { public: double pow(double x, int n) { int index = n; if (n == 0) return 1; if (n == 1) return x; if (n < 0) index = -n; double rev = index%2==0 ? pow(x*x, index>>1) : pow(x*x, index>>1)*x; if (n < 0) return 1 / rev; else return rev; } };
LeetCode:Pow(x, n),布布扣,bubuko.com
原文:http://www.cnblogs.com/kaituorensheng/p/3766209.html