1. 程式人生 > >leetcode筆記:Pow(x, n)

leetcode筆記:Pow(x, n)

asc 思路 leet 技術分享 solution tty lee pow(x processor

一. 題目描寫敘述

Implement pow(x, n).

二. 題目分析

實現pow(x, n)。即求xn次冪。

最easy想到的方法就是用遞歸直接求nx的乘積,這裏須要依據n的值,推斷結果是正數還是負數,這樣的方法的時間復雜度為O(n)

更加快捷的方法是。使用分治法。對於x^n。有一下公式:

x^n = x^(n / 2) *  x^(n / 2) * x^(n % 2)

使用這樣的方法的時間復雜度為O(logn)

三. 演示樣例代碼

#include <iostream>

using namespace std;

class
Solution { public: double pow(double x, int n) { if (n == 0) return 1; if (n > 0) return power(x, n); else return 1 / power(x, -1 * n); } private: double power(double x, int n) { if (n == 0) return
1; double a = power(x, n / 2); // 遞歸求x^(n/2) if (n % 2 == 0) return a * a; else return a * a * x; } };

技術分享

四. 小結

此題為分治思路的經典題型之中的一個。

‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); });

    leetcode筆記:Pow(x, n)