1 Star 0 Fork 0

蓝桥云课/python-100

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
076-bit.py 1.44 KB
一键复制 编辑 原始数据 按行查看 历史
xiaoyi733112 提交于 2020-03-17 16:00 . python-100 answer
def validate_index(func):
def validate_index_wrapper(self, *args, **kwargs):
for arg in args:
if arg < 0:
raise IndexError('Invalid index')
return func(self, *args, **kwargs)
return validate_index_wrapper
class Bit(object):
def __init__(self, number):
if number is None:
raise TypeError('number cannot be None')
self.number = number
@validate_index
def get_bit(self, index):
mask = 1 << index
return self.number & mask != 0
@validate_index
def set_bit(self, index):
mask = 1 << index
self.number |= mask
return self.number
@validate_index
def clear_bit(self, index):
mask = ~(1 << index)
self.number &= mask
return self.number
@validate_index
def clear_bits_msb_to_index(self, index):
mask = (1 << index) - 1
self.number &= mask
return self.number
@validate_index
def clear_bits_index_to_lsb(self, index):
mask = ~((1 << index + 1) - 1)
self.number &= mask
return self.number
@validate_index
def update_bit(self, index, value):
if value is None or value not in (0, 1):
raise Exception('Invalid value')
if self.get_bit(index) == value:
return self.number
if value:
self.set_bit(index)
else:
self.clear_bit(index)
return self.number
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/lanqiao-courses/python-100.git
git@gitee.com:lanqiao-courses/python-100.git
lanqiao-courses
python-100
python-100
master

搜索帮助