Created
February 17, 2013 13:31
-
-
Save pdu/4971502 to your computer and use it in GitHub Desktop.
Implement pow(x, n). http://leetcode.com/onlinejudge#question_50
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) { | |
| if (n == 0) | |
| return 1; | |
| else if (n == 1) | |
| return x; | |
| if (n < 0) { | |
| x = 1 / x; | |
| n = -n; | |
| } | |
| double xx = pow(x, n / 2); | |
| if (n % 2 == 0) | |
| return xx * xx; | |
| else | |
| return xx * xx * x; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment