- 题意:求a的n次方
- 考虑
- n有正有负,也可能为0
- n为负数,使用1/a的-n次方(n为-2147483648,但是-n最大到2147483647)
- 代码
class Solution { public: double myPow(double x, int n) { if (n == 0) return 1; else if (n > 0 ) return positivepow(x, n); else { if (n == -2147483648) return 1/positivepow(x, -(n+1))/x; else return 1/positivepow(x, -n); } } double positivepow(double x, int n) { double res = 1.0; double factor = x; while(n!=0) { if (n%2 == 1) { res = res * factor; } n = n/2; factor = factor * factor; } return res; } };
leetcode 50. Pow(x, n)
最新推荐文章于 2024-08-08 09:31:31 发布