Created
January 1, 2015 05:59
-
-
Save jones/f4dc1ef25643efec4a95 to your computer and use it in GitHub Desktop.
Implement pow(x, n).
This file contains 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: | |
# @param x, a float | |
# @param n, a integer | |
# @return a float | |
def pow(self, x, n): | |
if x == 0.0: | |
return 0.0 | |
if n < 0: | |
# Avoids arithmetic underflow | |
return 1.0/self.pow(x, -n) | |
if n == 0: | |
return 1.0 | |
elif n % 2 == 0: | |
return self.pow(x, n // 2) ** 2 | |
else: | |
return x * self.pow(x, n // 2) ** 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment