[Leetcode]50. Pow(x, n)
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode]50. Pow(x, n)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Implement pow(x,?n).
?
我的做法就比較傻了。排除了所有的特殊情況(而且double一般不可以直接判斷==),然后常規情況用循環來做。- -|||
直接用循環,時間復雜度就比較大。應該是用二分法來做。先計算pow(x,n/2)。然后再pow(x,n)=pow(x,n/2)*pow(x,n/2)
?
class Solution { public: double power(double x, int n){ if(n==0) return 1; double v = power(x,n/2); if(n%2 == 0) return v *v; else return v* v* x; }double myPow(double x, int n) {if(n<0) return 1.0 / power(x,-n); else return power(x,n); } };?
?
#define EPSINON 0.00001 #define Max 2147483647 #define Min -2147483648 #define DBL_MAX 1.7976931348623159e+308 class Solution { public:double myPow(double x, int n) {/*three special case*/if(n==1)return x;if(n==0)return 1.0;if(abs(x)==1.00000){if(n%2==0)return 1.0;else return x;}if(n>=Max){if(abs(x)<=EPSINON)return 0.0;elsereturn DBL_MAX;}if(n<=Min){if(abs(x)<=EPSINON)return DBL_MAX;elsereturn 0.0;}int size=abs(n);double tmp=x;for(int i=2;i<=size;i++){tmp*=x;}if(n>=0)return tmp;else return 1.0/tmp;} };?
轉載于:https://www.cnblogs.com/LUO77/p/5645127.html
總結
以上是生活随笔為你收集整理的[Leetcode]50. Pow(x, n)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android签名机制介绍:生成keys
- 下一篇: SSL介绍与Java实例