Implement pow(x, n).
刚开始没想到,后来看remlost的博客才写出来,代码很简练:
class Solution { public: double pow(double x, int n) { if(n<0) return 1/power(x,-n); else return power(x,n); } private: double power(double x, int n){ if(n==0) return 1; double v = power(x,n/2); if(n%2==0) return v*v; else return v*v*x; } };
[LeetCode] Pow(x, n) (二分法)
时间: 2024-10-13 11:18:24