LeetCode OJ Pow(x, n)

来源:互联网 发布:捡宝贝淘宝u站 编辑:程序博客网 时间:2024/06/07 01:58

Implement pow(xn).

calculate the pow of a double, use fast power and notice that the exponent may be negative.

class Solution {public:    double pow(double x, int n) {        if (n < 0) {  // for negative n            x = 1 / x;            n = -n;        }        if (n == 1) return x;  // when n = 1 in recursion, return itself        if (n == 0) return 1.0;  // n^0 = 1(n != 0)                /* fast power */        if (n & 1 == 1) {            return x * pow(x, n - 1);        } else {            double temp = pow(x, n / 2);            return temp * temp;        }    }};


0 0
原创粉丝点击