python - 如何在 Python3 中修复我的“添加函数使用按位运算符”代码?
问题描述
我想在 Python 中用按位运算符编写一个“add”函数,但在尝试计算“5 + (-3)”或“(-4) + 8”时遇到了一个错误。
我的 Python 版本是 3.7。
def bitwiseplus(x, y):
while y:
ans = x ^ y
y = (x & y) << 1
x = ans
return ans
执行 bitwiseplus(5, -3) 或 bitwiseplus(-4, 8) 时会超时。
解决方案
def bitwiseplus(x, y):
s, c, i = x ^ y, x & y, 1
# Max number of bits in the final answer
N = max(x.bit_length(), y.bit_length()) + 2
while i < N:
s, c, i = s ^ (c << 1), s & (c << 1), i + 1
# An overflow is detected if we have x carry out of the final addition
# If so, the sum should be zero.
if c ^ (1 << (N - 1)) == 0:
return 0
# If the final answer is positive (we check if MSB of answer is 0)
# then keep only lower N bits of answer. This is needed since we abort
# the ripple addition above once we know we have calculated enough bits
if not (s >> (N - 1)) & 1:
# ~(~0 << N) will generate 'N' ones with leading zeros.
# For example N=3 gives 0xb00111
s = s & ~(~0 << N)
return s
print (bitwiseplus(5,-3))
输出:
2
推荐阅读
- python - 在 Python IGraph 中将顶点作为元组获取
- windows - 如何在 WinSCP 脚本中启用日志记录?
- mysql - MySQL选择以NULL分隔的数据系列之间的日期范围
- javascript - FeathersJS:在服务测试中注入 HTTP 标头
- html - 如何让两个列表项出现在页面的另一侧?
- node.js - 如何将多个图像上传到 Sails.js 应用程序
- c++ - 为什么在带有 gcc5 的 macosx Mojave 10.14 中缺少 charconv 标头?
- domain-driven-design - DDD 关于设计决策
- reactjs - 打字稿:定义嵌套对象的接口“需要一个键”
- spring-boot - 无法为使用 maven-shaded-plugin 创建的 jar 获取条目 BOOT-INF/lib 的嵌套存档