第14天 位运算
190.颠倒二进制位
思路:
1、这道题的输入实际上是一个整数。 整数末位跟1做与操作,不断右移,存入list,最后把list中的内容转化为字符串,然后再用int(s,2)转换为整数。
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
ans = [] #由于str类型不能更改 所以先用list存储
x = 32 #循环32次
while(x): #注意这里不能while(n),因为n的末尾几位可能都为0,这样就直接退出了。
ans.append(str(n&1))
n>>=1
x -= 1
s = ''.join(ans)
y = int(s,2) #把二进制字符串转换为整数
return y
2、完全用位运算,用与1操作算末位,用或操作填上末位,用左移替代*2的n次幂,用右移代替除以2的n次幂。
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
res = 0
for i in range(32):
tmp = n & 1 #算n的最后一位是1还是0
res = res << 1 #把res左移一位以便在末尾填上下一位
res = res | tmp #用或操作填上末尾一位
n = n >> 1 #n右移一位
return res
136.只出现一次的数字
思路:
1、用字典记录次数,由于要么2次要么1次,2次直接删除。最后剩的就是出现只有1次的。
字典的常见操作:(1)、dict.setdefault(i,0)设定初始化值 (2)dict.keys()以列表形式返回所有的key值(3)dict.values()以列表形式返回所有 的value值。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic = {}
for i in nums:
dic.setdefault(i,0)
dic[i] += 1
if dic[i] == 2:
del dic[i]
return dic.keys()[0]
2、位运算
所有数字按位异或后剩下的就是只出现一次的数字。
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
ans = nums[0]
for i in nums[1:]:
ans ^= i #按位异或
return ans