Monday, October 21, 2013

Solution to LeetCode Problems: Pow(x,n)

Pow(x, n)

Implement pow(x, n).

Thought:
1. Do it by loop.
2. Divide and conqueror, so the number of multiplications is reduced by half.

Solution:
  1. class Solution {  
  2. public:  
  3.     double pow_proc(double x, int n) {  
  4.         double p;  
  5.         switch(n)  
  6.         {  
  7.             case 0:  
  8.                 return 1;  
  9.             case 1:  
  10.                 return x;  
  11.             default:  
  12.                 p=pow_proc(x, n/2);  
  13.                 if ((n & 1) == 0)  
  14.                     return p*p;  
  15.                 else  
  16.                     return p*p*x;  
  17.         }  
  18.     }  
  19.       
  20.     double pow(double x, int n)  
  21.     {  
  22.         if (n < 0)  
  23.             return 1.0/pow_proc(x, -n);  
  24.         else  
  25.             return pow_proc(x, n);  
  26.     }  
  27. };  

No comments:

Post a Comment