快速幂
求解 x的n次方
class Solution { public: double myPow(double x, int n) { if(n == 0 || x == 1) return 1; double ans = 1; long k = n; if(k < 0){ k = -k; x = 1/x; } while (k){ if (k & 1) ans *= x; k >>= 1; x = x * x; } return ans; } };
求解 x的n次方
class Solution { public: double myPow(double x, int n) { if(n == 0 || x == 1) return 1; double ans = 1; long k = n; if(k < 0){ k = -k; x = 1/x; } while (k){ if (k & 1) ans *= x; k >>= 1; x = x * x; } return ans; } };