Ale*_*lex 3 python math binary
我有两个数字(二进制或不二进制,不起任何作用),只有一位不同,例如(伪代码)
a = 11111111
b = 11011111
Run Code Online (Sandbox Code Playgroud)
我想要一个简单的python函数,它返回不同的位位置(给定示例中的"5",从右到左).我的解决方案是(python)
math.log(abs(a-b))/math.log(2)
Run Code Online (Sandbox Code Playgroud)
但我想知道是否有更优雅的方法来做到这一点(不使用花车等).
谢谢Alex
您可以使用二进制独占:
a = 0b11111111
b = 0b11011111
diff = a^b # 0b100000
diff.bit_length()-1 # 5 (the first position (backwards) which differs, 0 if a==b )
Run Code Online (Sandbox Code Playgroud)