Saturday, March 16, 2013

Pow(x, n)

/*
Pow(x, n)
Implement pow(x, n).
*/
class Solution {
public:
    double abs(double x){
      if(x<0) return (-1)*x;
      return x;
    }
    double pow(double x, int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(n==0) return 1;
        if(x==0) return 0;
        if(x==1) return 1;
        if(x==-1){
          if(n%2==0) return 1;
          else return -1;
        }
        bool neg = false;
        if(n<0) {
          neg = true;
          n = -n;
        }
        int i = 1;
        double result = x;
        while(i<n){
          result = x*result;
          i++;
          if(abs(result)<0.00000001 || abs(result) > 1000000) break;
        }
        if(neg) result = 1/result;
        return result;
    }
};

No comments:

Post a Comment