Created
March 21, 2013 17:23
-
-
Save zhoutuo/5214853 to your computer and use it in GitHub Desktop.
Implement pow(x, n).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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