Leetcode 50. Pow(x, n)
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 50. Pow(x, n)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
50. Pow(x, n)
Total Accepted:?96891?Total Submissions:?348858?Difficulty:?Medium?
Implement pow(x,?n).
?
?
思路:分情況討論:
1.n=0,返回1
2.n<0,轉換為n>0的情況處理
3.n>0,舉個例子:n=19時。
19=10011,所以x^19=x^10011=x^(10000+10+1)。所以只要看n的最末尾是否為1,如果為1,則累乘當前的x。每個循環,x=x*x,n=n>>1(n/2)。
?
注意:int的最小值INT_MIN=-2147483648,int的最大值INT_MAX=2147483647,可以看到INT_MIN!=INT_MAX;
?
代碼:
迭代:
1 class Solution { 2 public: 3 double myPow(double x, int n) { 4 if(n<0){ 5 if(n==INT_MIN) return 1.0/(x*myPow(x,INT_MAX)); 6 return 1.0/myPow(x,-n); 7 } 8 if(n==0){ 9 return 1; 10 } 11 double product=1; 12 for(;n>0;x*=x,n=n>>1){ 13 if(n&1){ 14 product*=x; 15 } 16 } 17 return product; 18 } 19 };
?
?
遞歸:
1 class Solution { 2 public: 3 double myPow(double x, int n) { 4 if(n==0) return 1.0; 5 double product=myPow(x,n/2); 6 product*=product; 7 if(n<0){ 8 x=1/x; 9 } 10 return (n%2==0)?product:product*x; 11 } 12 };
?
轉載于:https://www.cnblogs.com/Deribs4/p/5635301.html
總結
以上是生活随笔為你收集整理的Leetcode 50. Pow(x, n)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 以何开头的成语有哪些啊?
- 下一篇: MongoDB(一):安装