runnig

Implement Pow(x,n)

Feb 6th, 2013
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.72 KB | None | 0 0
  1. // http://leetcode.com/onlinejudge#question_50
  2. // Implement pow(x,n)
  3.  
  4. #include <cfloat>
  5.  
  6. class Solution {
  7. public:
  8.     bool eq(const double & x, const double & y)
  9.     {
  10.         return std::abs(x-y) < 0.000001;
  11.     }
  12.     double pow(double x, int n) {
  13.         return pow0(x,n);
  14.     }
  15.     double pow0(double x, int n) {
  16.         if(n==0) { return 1.0; }  
  17.         if(eq(x, 0.0) || eq(x,1.0) || n==1 ) { return x; }
  18.         if(eq(x, -1.0))
  19.         {
  20.             if(n%2 == 0) { return 1.0; }
  21.             else { return -1.0; }
  22.         }
  23.         if(n<0) { return 1.0/pow0(x,-n); }
  24.        
  25.         const double y = pow0(x,n/2);
  26.         double r = y * y;
  27.         if(n%2 != 0)  { r *= x; }
  28.         return r;
  29.     }
  30. };
Advertisement
Add Comment
Please, Sign In to add comment