Skip to content

Instantly share code, notes, and snippets.

@zhoutuo
Created March 21, 2013 17:23
Show Gist options
  • Save zhoutuo/5214853 to your computer and use it in GitHub Desktop.
Save zhoutuo/5214853 to your computer and use it in GitHub Desktop.
Implement pow(x, n).
class Solution {
public:
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(n < 0) {
if(n == -2147483648) {
return pow(1 / x, -(n + 1)) / x;
}
return pow(1 / x, -n);
}
double res = pow(x, n >> 1);
if(n >> 1 << 1 == n) {
x = res * res;
} else {
x = res * res * x;
}
return x;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment