传送门
nowcoder
leetcode
题目描述
实现函数 double Power(double base, int exponent),求 base 的 exponent 次方。
不得使用库函数,同时不需要考虑大数问题。
C++ 代码 - nowcoder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
class Solution { public: double Power(double base, int exp) { if (exp == 0) return 1.0; if (base == 0) return 0.0;
bool isNegative = false; if (exp < 0) { exp = -exp; isNegative = true; }
double res = Power(base * base, exp / 2); if ((exp & 1) == 1) { res *= base; } return isNegative ? 1 / res : res; } };
double Power(double base, int exponent) { if (exponent == 0) return 1.0; if (base == 0.0) return 0.0;
bool isNegative = false; if (exponent < 0) { exponent *= -1; isNegative = true; }
double res = base; for (int i = 2; i <= exponent; i ++) { res *= base; } return isNegative ? 1 / res : res; }
class Solution { public: double Power(double base, int exponent) { if (exponent == 0) return 1.0; if (base == 0.0) return 0.0;
long exp = exponent; if (exponent < 0) { exp = exponent * (-1.0); }
double res = 1.0; while (exp != 0) { if ((exp & 1) == 1) { res *= base; } base *= base; exp >>= 1; } return exponent < 0 ? 1 / res : res; } };
|
C++ 代码 - leetcode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
|
class Solution { public: double myPow(double x, int n) { if (n == 0) return 1.0;
long exp = n; bool isNegative = false; if (n < 0) { exp = n * (-1.0); isNegative = true; }
double res = myPow(x * x, exp / 2); if ((exp & 1) == 1) { res *= x; } return isNegative ? 1 / res : res; } };
class Solution { public: double myPow(double x, int n) { if (n == 0) return 1.0; if (x == 0.0) return n;
long exp = n; if (n < 0) { exp = n * (-1.0); }
double res = 1.0; while (exp) { if ((exp & 1) == 1) { res *= x; } x *= x; exp >>= 1; } return n < 0 ? 1 / res : res; } };
|