理论部分
练习部分
3. 课后思考题
4. leetcode练习题
(把数字当作二进制数进行运算)
注:了解二进制转换原理,了解相关应用场景。学习时参考阅读
位运算1
位运算2
应用:
1、与运算通常应用的场景是获取某一位的值为1还是0(如判断奇数偶数,统计数值中1的个数);
2、左移右移特性:左移一位相当于乘以2,右移一位相当于除以2;
3、异或特性:任意数和自身异或结果为0;0和任意数异或结果还是其本身。
位运算运用
x, y = 4, 5
small = x if x < y else y
print(small) # 4
letters = ['A', 'B', 'C', 'D', 'E', 'F', 'G']
if 'A' in letters:
print('A' + ' exists')
if 'h' not in letters:
print('h' + ' not exists')
# A exists
# h not exists
a = "hello"
b = "hello"
print(a is b, a == b)
# True True
a = ["hello"]
b = ["hello"]
print(a is b, a == b)
# False True
注意:
https://blog.csdn.net/pc_286/article/details/50111499
表格来源:https://blog.csdn.net/weixin_43353539/article/details/89444838
print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
【例子】没有参数时,每次输出后都会换行。
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed without 'end'and 'sep'.")
for item in shoplist:
print(item)
# This is printed without 'end'and 'sep'.
# apple
# mango
# carrot
# banana
【例子】每次输出结束都用end 设置的参数& 结尾,并没有默认换行。
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'end='&''.")
for item in shoplist:
print(item, end='&')
print('hello world')
# This is printed with 'end='&''.
# apple&mango&carrot&banana&hello world
【例子】item 值与’another string’ 两个值之间用sep 设置的参数& 分割。由于end 参数没有设置,因此默认是输出解释后换行,即end 参数的默认值为\n 。
shoplist = ['apple', 'mango', 'carrot', 'banana']
print("This is printed with 'sep='&''.")
for item in shoplist:
print(item, 'another string', sep='&')
# This is printed with 'sep='&''.
# apple&another string
# mango&another string
# carrot&another string
# banana&another string
练习题:
给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。尝试使用位运算解决此题。
list_ = [1,1,2,2,3,3,4,5,5]
res = 0
for i in list_ :
res = res ^ i
print(res)
class Solution:
def singleNumber(self, nums: List[int]) -> int:
# your code here
one=0
for num in nums:
one=one^num
return one
本文仅是阅读后的记录、搜集、整理,仅供参考。