LeetCode 50. Pow(x, n)(二分查找)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 50. Pow(x, n)(二分查找)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 二分查找
- 2.1 遞歸
- 2.2 循環
1. 題目
實現 pow(x, n) ,即計算 x 的 n 次冪函數。
示例
輸入: 2.00000, 10
輸出: 1024.00000
示例
輸入: 2.00000, -2
輸出: 0.25000
解釋: 2-2 = 1/22 = 1/4 = 0.25
說明:
-100.0 < x < 100.0
n 是 32 位有符號整數,其數值范圍是 [?231, 231 ? 1] 。
來源:力扣(LeetCode) 鏈接:https://leetcode-cn.com/problems/powx-n
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
《劍指Offer》同題:面試題16. 數值的整數次方…
2. 二分查找
類似題解:LeetCode 372. 超級次方(快速冪)
2.1 遞歸
class Solution { public:double myPow(double x, int n) {if(n == 0) return 1.0;long N = n;if(N < 0){x = 1/x;N = -N;}return POW(x, N);}double POW(double x, int N) {if(N == 0) return 1.0;double half = POW(x, N/2);if(N%2 == 0)return half*half;elsereturn half*half*x;} }; class Solution {//超時,0.00001,2147483647unordered_map<int ,double> m; public:double myPow(double x, int n) {if(n == 0)return 1.0;long N = n;if(n < 0){x = 1/x;N = -(long)n;//INT_MIN換號后溢出}return MyP(x, N);}double MyP(double x, long N) {if(N == 0)return 1.0;if(N%2 == 0){if(m.count(N))return m[N];double a = MyP(x, N/2)*MyP(x, N/2);m[N] = a;return a;}else{if(m.count(N))return m[N];double b = MyP(x, N/2)*MyP(x, N/2)*x;m[N] = b;return b;}} };2.2 循環
class Solution { public:double myPow(double x, int n) {if(n == 0) return 1.0;long N = n;if(N < 0){x = 1/x;N = -N;}double ans=1;double product = x;for(long i = N; i; i /= 2){if(i % 2 == 1)ans *= product;product *= product;}return ans;} };總結
以上是生活随笔為你收集整理的LeetCode 50. Pow(x, n)(二分查找)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 1403. 非递增顺序
- 下一篇: 基于sklearn的LogisticRe