50. Pow(x, n)
问题:
实现x^n的幂运算。
Example 1: Input: 2.00000, 10 Output: 1024.00000 Example 2: Input: 2.10000, 3 Output: 9.26100 Example 3: Input: 2.00000, -2 Output: 0.25000 Explanation: 2-2 = 1/22 = 1/4 = 0.25 Note: -100.0 < x < 100.0 n is a 32-bit signed integer, within the range [−2^31, 2^31 − 1]
解法:bit位方法
使用bit位方法,可以将计算速度提升一半
The basic idea is to decompose the exponent into powers of 2, so that you can keep dividing the problem in half. N = 9 = 2^3 + 2^0 = 1001 in binary. Then: x^9 = x^(2^3) * x^(2^0)
从2^0->2^n 升序判断幂N的bit位。
- initial:
- res=1
- bit[0]=1:
- res=res*x
- X=x^2
- bit[1]=0:
- res
- X=(x^2)^2=x^(2^2)=x^4
- bit[2]=0:
- res
- X=(x^4)^2=x^(2^3)=x^8
- bit[3]=1:
- res=res*x
- X=(x^8)^2=x^(2^4)=x^16
代码参考:
1 class Solution { 2 public: 3 double myPow(double x, int n) { 4 double res=1; 5 long pn = abs(n); 6 while(pn>0) { 7 if(pn&1) res*=x; 8 pn = pn>>1; 9 x*=x; 10 } 11 return n>=0?res:1/res; 12 } 13 };