Python pow(x,n) Leetcode NO.50 分而治之
class
Solution
(
object
)
:
def
myPow
(
self
,
x
,
n
)
:
"""
:type x: float
:type n: int
:rtype: float
"""
if
n
==
0
:
return
1
if
n
<
0
:
return
1
/
self
.
myPow
(
x
,
-
n
)
if
n
%
2
==
1
:
return
x
*
self
.
myPow
(
x
,
n
-
1
)
return
self
.
myPow
(
x
*
x
,
n
/
2
)
class
Solution
(
object
)
:
def
myPow
(
self
,
x
,
n
)
:
"""
:type x: float
:type n: int
:rtype: float
"""
if
n
<
0
:
x
=
1
/
x
n
=
-
n
p
=
1
#&位运算,>>向右移动1位(也就是除以2)
while
n
:
if
n
&
1
:
p
*=
x
x
*=
x
n
>>
=
1
return
p