Leetcode: Pow(x, n)

來源:互聯網
上載者:User

標籤:style   blog   color   io   os   ar   for   div   sp   

Implement pow(x, n).

Analysis:

The most basic idea, x multiply itself n time and return.  However, this strait forward approach got time excessed. O(n).

Note that O(logn)< O(n)<O(n^2)<O(2^n).  Therefore, we should consider about recursive approach, and divide n by 2 for each recursive call.

 1 public class Solution { 2     public double pow(double x, int n) { 3         if (n < 0) { 4             return 1/helper(x, -n); 5         } 6         else return helper(x, n); 7     } 8      9     public double helper(double x, int n) {10         if (n == 0) return 1;11         double half = helper(x, n/2);12         if (n%2 == 0) {13             return half*half;14         }15         else return half*half*x;16     }17 }

參考網上的想法,把x的n次方劃分成兩個x的n/2次方相乘,然後遞迴求解子問題,結束條件是n為0返回1。因為是對n進行二分,演算法複雜度和上面方法一樣,也是O(logn)。

Leetcode: Pow(x, n)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.