Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://leetcode.com/onlinejudge#question_50
- // Implement pow(x,n)
- #include <cfloat>
- class Solution {
- public:
- bool eq(const double & x, const double & y)
- {
- return std::abs(x-y) < 0.000001;
- }
- double pow(double x, int n) {
- return pow0(x,n);
- }
- double pow0(double x, int n) {
- if(n==0) { return 1.0; }
- if(eq(x, 0.0) || eq(x,1.0) || n==1 ) { return x; }
- if(eq(x, -1.0))
- {
- if(n%2 == 0) { return 1.0; }
- else { return -1.0; }
- }
- if(n<0) { return 1.0/pow0(x,-n); }
- const double y = pow0(x,n/2);
- double r = y * y;
- if(n%2 != 0) { r *= x; }
- return r;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment