翻转整数中的一位随机位
我想翻转整数中的一位。所以我必须将整数转换为二进制,然后翻转一个随机位,然后将其转换回整数。我怎么能这么做呢?
# what I want to get:
# num = 8 ... 1000
# new_num = flip_one_bit(num)
# it flips one random bit in 1000 -> 0000 or 1010 or 1100, ...
# returns back it's decimal value 0000 = 0; 1010 = 10
from random import randint
def flip_one_bit(num: int) -> int:
b_num = bin(num)
# flip one bit than convert back to integer
return b_num
附带问题:有没有办法将二进制转换为整数而不构建我自己的函数(任何内置函数)?这样做的“好方法”是什么?
I would like to flip one bit in integer. So I have to convert integer to binary, than flip one random bit and than convert it back to integer. How could i do that?
# what I want to get:
# num = 8 ... 1000
# new_num = flip_one_bit(num)
# it flips one random bit in 1000 -> 0000 or 1010 or 1100, ...
# returns back it's decimal value 0000 = 0; 1010 = 10
from random import randint
def flip_one_bit(num: int) -> int:
b_num = bin(num)
# flip one bit than convert back to integer
return b_num
Side question: Is there any way to convert binary to integer without building my own function (anything built-in)? What's the "good way" of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
无需使用字符串:
No need to work with strings:
您可以将
int
与base
参数一起使用,将二进制字符串转换为其相应的 int。You can use
int
with abase
parameter to convert a binary string to its corresponding int.