Skip to content

Instantly share code, notes, and snippets.

@jones
Created January 1, 2015 05:59
Show Gist options
  • Save jones/f4dc1ef25643efec4a95 to your computer and use it in GitHub Desktop.
Save jones/f4dc1ef25643efec4a95 to your computer and use it in GitHub Desktop.
Implement pow(x, n).
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