python一行代码经常return 和/或者 之前做过一道巧用逻辑运算的题。把它找出来
剑指offer56-Ⅰ 数组中数字只出现一次,其他数字出现两次
class Solution:
def singleNumbers(self
, nums
: List
[int]) -> List
[int]:
a
,b
,res
=0,0,0
for n
in nums
:
res
^=n
h
=1
while (res
&h
==0):
h
<<= 1
for n
in nums
:
if (n
&h
==0):
a
^=n
else:
b
^=n
return [a
,b
]
剑指offer56-Ⅱ 数组中数字只出现一次,其他数字出现三次
class Solution:
def singleNumber(self
, nums
: List
[int]) -> int:
count
=[0]*32
for n
in nums
:
for j
in range(32):
count
[j
]+=n
&1
n
>>= 1
res
,m
=0,3
for i
in range(32):
res
<<= 1
res
|= count
[31-i
]%m
return res
if count
[31]%m
==0 else ~(res
^0xffffffff)
由于 Python 的存储负数的特殊性,需要先将
000 - 323232 位取反(即 res
^ 0xffffffff ),再将所有位取反(即
~ )。
两个组合操作实质上是将数字
323232 以上位取反,
000 - 323232 位不变
剑指offer65-不用四则运算做加法
o(1) o(1)
class Solution:
def add(self
, a
: int, b
: int) -> int:
x
= 0xffffffff
a
,b
= a
& x
,b
&
while b
!= 0:
a
,b
= a
^ b
,a
& b
<< 1 & x
return a
if a
<= 0x7fffffff else ~(a
^ x
)
转载请注明原文地址:https://ipadbbs.8miu.com/read-30780.html