Solution:
Judge Small:
class Solution {
public:
double pow(double x, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
double sol = 1;
while (n > 0) {
sol *= x;
n--;
}
while (n < 0) {
sol /= x;
n++;
}
return sol;
}
};
Judge Large:
class Solution {
public:
double my_pow(double a, int b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(b==0) return 1;
if(b==1) return a;
double temp= my_pow(a,b/2);
temp=temp*temp;
return ((b%2==0)? temp : temp*a);
}
double pow(double x, int e) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(e>=0) {
return my_pow(x, e);
} else {
return 1/my_pow(x,e);
}
}
};
=================== Updated ==========
class Solution {
public:
double myPow(double x, int n) {
double ans = 0;
if (x == 1) {
return x;
}
if (x == -1 && n == INT_MIN) {
return 1;
}
if ((x == 0 && n <= 0) || (n == INT_MIN)) {
return ans;
}
if (n == 1) {
return x;
}
if (n == 0) {
return 1;
} else if (n > 0) {
double partial = myPow(x, n/2);
ans = partial * partial;
if ((n % 2) == 1) {
ans *= x;
}
return ans;
} else {
return 1/myPow(x, -n);
}
}
};
Judge Small:
class Solution {
public:
double pow(double x, int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
double sol = 1;
while (n > 0) {
sol *= x;
n--;
}
while (n < 0) {
sol /= x;
n++;
}
return sol;
}
};
Judge Large:
class Solution {
public:
double my_pow(double a, int b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(b==0) return 1;
if(b==1) return a;
double temp= my_pow(a,b/2);
temp=temp*temp;
return ((b%2==0)? temp : temp*a);
}
double pow(double x, int e) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(e>=0) {
return my_pow(x, e);
} else {
return 1/my_pow(x,e);
}
}
};
=================== Updated ==========
class Solution {
public:
double myPow(double x, int n) {
double ans = 0;
if (x == 1) {
return x;
}
if (x == -1 && n == INT_MIN) {
return 1;
}
if ((x == 0 && n <= 0) || (n == INT_MIN)) {
return ans;
}
if (n == 1) {
return x;
}
if (n == 0) {
return 1;
} else if (n > 0) {
double partial = myPow(x, n/2);
ans = partial * partial;
if ((n % 2) == 1) {
ans *= x;
}
return ans;
} else {
return 1/myPow(x, -n);
}
}
};
No comments:
Post a Comment