【问题标题】:int 111 to binary 111(decimal 7)整数 111 到二进制 111(十进制 7)
【发布时间】:2020-10-26 02:28:50
【问题描述】:

问题:以数字为例 37 是(二进制 100101)。 计算二进制 1 并创建一个类似 (111) 的二进制文件并打印该二进制文件的十进制数 (7)

num = bin(int(input()))
st = str(num)
count=0

for i in st:
    if i == "1":
        count +=1

del st
vt = ""
for i in range(count):
    vt = vt + "1"
vt = int(vt)
print(vt)

我是新手,卡在这里。

【问题讨论】:

  • 欢迎来到 SO。请提供有关您的问题的详细信息和minimal-reproducible-example。输入和预期输出的一些示例总是有用的。请查看how-to-ask 问题以了解更多详情。

标签: python binary int


【解决方案1】:

我不会推荐你的方法,但要说明你哪里出错了:

num = bin(int(input()))
st = str(num)
count = 0

for i in st:
    if i == "1":
        count += 1

del st
# start the string representation of the binary value correctly
vt = "0b"
for i in range(count):
    vt = vt + "1"
# tell the `int()` function that it should consider the string as a binary number (base 2)
vt = int(vt, 2)
print(vt)

请注意,下面的代码与您的代码完全相同,但更简洁:

ones = bin(int(input())).count('1')
vt = int('0b' + '1' * ones, 2)
print(vt)

它对字符串使用标准方法count() 来获取ones 中的个数,并利用Python 使用乘法运算符* 多次重复字符串的能力。

【讨论】:

    【解决方案2】:

    获得所需的二进制文件后尝试此操作。

    def binaryToDecimal(binary): 
      
    binary1 = binary 
    decimal, i, n = 0, 0, 0
    while(binary != 0): 
        dec = binary % 10
        decimal = decimal + dec * pow(2, i) 
        binary = binary//10
        i += 1
    print(decimal)
    

    【讨论】:

    • @YangHG - 我也是 python 新手。谢谢你的信息
    【解决方案3】:

    一行:

    print(int(format(int(input()), 'b').count('1') * '1', 2))
    

    让我们从里到外分解它:

    format(int(input()), 'b')
    

    这个built-in function 从输入中获取一个整数,并根据Format Specification Mini-Language 返回一个格式化的字符串。在这种情况下,'b' 参数为我们提供了二进制格式。

    那么,我们有

    .count('1')
    

    这个str method返回'1'format函数返回的字符串中出现的总次数。

    在 Python 中,您可以将一个字符串乘以一个数字,以将相同的字符串重复连接 n 次:

    x = 'a' * 3
    print(x)  # prints 'aaa'
    

    因此,如果我们将count 方法返回的数字乘以字符串'1',我们将得到一个字符串,该字符串仅包含1,并且仅包含与原始二进制输入数字相同数量的1。现在,我们可以通过将其转换为以 2 为底的二进制数来表示这个数字,如下所示:

    int(number_string, 2)
    

    所以,我们有

    int(format(int(input()), 'b').count('1') * '1', 2)
    

    最后,让我们打印整个内容:

    print(int(format(int(input()), 'b').count('1') * '1', 2))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-22
      • 2021-05-18
      • 2017-01-27
      • 1970-01-01
      • 2012-10-08
      • 1970-01-01
      • 2015-01-21
      • 1970-01-01
      相关资源
      最近更新 更多