1. 程式人生 > 其它 >【LeetCode】【遞迴】劍指 Offer 16. 數值的整數次方 思路解析和程式碼

【LeetCode】【遞迴】劍指 Offer 16. 數值的整數次方 思路解析和程式碼

技術標籤:LeetCode演算法leetcode資料結構

劍指 Offer 16. 數值的整數次方

題目連結

個人思路

思路

採用快速冪的方法,但中間有很多細節沒有注意到

  • 負指數問題——需要求倒數(注意0沒有倒數)
  • 負底數問題——需要判斷指數的奇偶性
  • 大數指數問題——需要對指數取模(本題沒有要求用long long,因此,超過一定範圍的指數就不需要再計算了)

程式碼優化

  • &運算來判斷奇偶性,注意&和“==”的優先順序,應寫為(n&1) == 1
  • “>>” 右移做除2運算

個人錯誤思路程式碼

快速冪程式碼錯了!!!!

class Solution {
public
: double ans = 1.0; bool flag = true;//預處理 double myPow(double x, int n) { if(flag == true){ if(n < 0){//指數為負數特判 x = 1 / x; n *= -1; } if((x < 0.0) && (n % 2 == 0)){ x *= -1; } if
(x == 1 || n == 0){ return 1.0; } flag = false; } if(ans < 0.000001 && x >= 0){ return 0; } if(n == 0){ return 1.0; } if(n & 1 == 1){ n = n >> 1; ans = myPow
(x, n) * myPow(x, n) * x; return ans; }else{ n = n >> 1; ans = myPow(x, n) * myPow(x, n); return ans; } } };

正確思路程式碼

class Solution {
public:
    double ans = 1.0;
    const int MOD = 1e9 + 7;
    double poww(double x, int n){
        //快速冪部分
        if(n == 0){
            return 1.0;
        }
        if((n & 1)){
            return myPow(x, n - 1) * x;
        }else{
            n = n >> 1;
            double result = myPow(x, n);
            return result * result;
        }
    }


    double myPow(double x, int n) {
        n = n % MOD;
        if(n < 0){//指數為負數特判
            x = 1 / x;
            n *= -1;
        }
        if((x < 0.0) && (!(n & 1))){
            x *= -1;
        }
        return poww(x, n);
    }
};