Leetcode | Pow(x, n)
Implement pow(x, n).
快速求幂,注意n是负数的情况。
1 class Solution { 2 public: 3 double pow(double x, int n) { 4 double ans = 1.0; 5 int symbol = 1; 6 if (n < 0) { 7 symbol = -1; 8 n = -n; 9 } 10 for (; n > 0; n >>= 1) { 11 if (n & 0x01) ans *= x; 12 x *= x; 13 } 14 if (symbol < 0) return 1/ ans; 15 else return ans; 16 } 17 };