This is a Leetcode problem:
Implement
pow(x, n)
, which calculatesx
raised to the powern
(\$x^n\$).Note -
-100.0 <
x
< 100.0
n
is a 32-bit signed integer, within the range [\$-2^{31}\$, \$2^{31}\$ − 1]
def pow(x, n):
if n == 0:
return 1
if x == 0 and n < 0:
return
result = 1
if n > 0:
while n > 0:
pre_result = result
result *= x
if pre_result == result or pre_result == -result:
if result >= 0:
return result
if n % 2 == 0:
return -result
else:
return result
n -= 1
return result
else:
while n < 0:
pre_result = result
result /= x
if pre_result == result or pre_result == -result:
if result >= 0:
return result
if n % 2 == 0:
return -result
else:
return result
n += 1
return result
NOTE - My solution is \$O(n)\$.
Here are some example inputs/outputs:
#print(pow(2.00000, 10))
>>> 1024.0
#print(pow(2.10000, 3))
>>> 9.261
#print(pow(2.00000, -2))
>>> 0.25
#print(pow(-1.00000, -2147483648))
>>> 1.0
Here are the times taken for each output:
#%timeit pow(2.00000, 10)
>>> 1.88 µs ± 14 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
#%timeit pow(2.10000, 3)
>>> 805 ns ± 17.2 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
#%timeit pow(2.00000, -2)
>>> 643 ns ± 9.55 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
#%timeit pow(-1.00000, -2147483648)
>>> 594 ns ± 20 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
So, I would like to know whether I could make this program shorter and more efficient.
Any help would be highly appreciated.
pow()
function. \$\endgroup\$pow()
function. \$\endgroup\$pow(10.0, 1000000)
returnsinf
. \$\endgroup\$