標籤:style blog color 2014 問題 演算法
實現浮點類型的冪運算,函數原型為:
double pow(double x, int n)
在求解這個問題的時候是一個很掙紮的過程,因為它不是報錯而是一直提示你超出時間,那麼必須一次次的考慮怎樣降低時間複雜度。
首先最直接的思路是下面這樣的,就跟直觀的數學求解一樣。
double pow(double x, int n){if(n==0)return 1.0;if(n<0)return 1.0/pow(x,-n);return x*pow(x,n-1);}
但是會提示你超出時間,這是可以理解的,因為時間複雜度是O(n)。對於較大的n這是不可接受的。
其次,考慮到n個x相乘式子的對稱關係,可以對上述方法進行改進,從而得到一種時間複雜度為O(logn)的方法,遞迴關係可以表示為pow(x,n) = pow(x,n/2)*pow(x,n-n/2)。
double pow(double x, int n){if(n==0)return 1.0;if(n<0)return 1.0/pow(x,-n);double half = pow(x,n>>1);if(n%2==0)return half*half;elsereturn half*half*x;}
這樣時間複雜度降低了一個數量級,但是仍然會逾時。
最後,網上搜答案查到下面的解決方案,這根編程之美中求1的個數很類似。只不過加了一步數學冪轉化為乘法,即指數相加的過程。
描述如下:
Consider the binary representation of n. For example, if it is "10001011", then x^n = x^(1+2+8+128) = x^1 * x^2 * x^8 * x^128. Thus, we don‘t want to loop n times to calculate x^n. To speed up, we loop through each bit, if the i-th bit is 1, then we add x^(1 << i) to the result. Since (1 << i) is a power of 2, x^(1<<(i+1)) = square(x^(1<<i)). The loop executes for a maximum of log(n) times.
該方法通過掃描n的二進位表示形式裡不同位置上的1,來計算x的冪次。
double my_pow(double x, int n){if(n==0) return 1.0;if(n<0)return 1.0 / pow(x,-n);double ans = 1.0 ;for(; n>0; x *= x, n>>=1){if(n&1>0)ans *= x;}return ans;}
這裡有一個問題就是當n等於INT_MIN時,求絕對值之後會超出整數範圍,因為負數是比正數多一個的。在這裡作為一個邊界添加考慮即可。
if(n<0) { if(n==INT_MIN) return 1.0 / (pow(x,INT_MAX)*x); else return 1.0 / pow(x,-n); }