标签:for ++ rest des public pow bsp pre nbsp
Implement pow(x, n).
AC: class Solution { public: double pow(double x, int n) { if(x == 0 && n == 0) return 1; if(x == 0) return 0; if(n == 0) return 1; if(n < 0){ return 1/x * pow(1/x, -(n+1)); } // n < 32 直接求解,要不然会递归太深,真是醉了。。。 if(n < 32){ double tmp = 1; for(int i = 0; i < n; i++){ tmp = tmp * x; } return tmp; } double tmp = pow(x, n/2); if(n % 2 == 1) return tmp * tmp *x; return tmp * tmp; } };
class Solution { public: double pow(double x, int n) { if (x == 0 && n < 0) return 0; double res = powCore(x, abs(n)); if (n < 0) return static_cast<double>(1 / res); return res; } double powCore(double x, int n) { if (n == 1) return x; if (n == 0) return 1; double resTem = powCore(x, n / 2)*powCore(x, n / 2); if (n % 2) resTem *= x; return resTem; } };
标签:for ++ rest des public pow bsp pre nbsp
原文地址:https://www.cnblogs.com/zl1991/p/9653026.html