【问题标题】:convert a given decimal number to binary and count the consecutive 1s and display it将给定的十进制数转换为二进制并计算连续的 1 并显示它
【发布时间】:2017-05-20 13:18:32
【问题描述】:

问题:将给定的十进制数转换为二进制并计算连续的1并显示它

示例案例 1: 5的二进制表示是101,所以连续1的最大个数是1。

示例案例 2: 13 的二进制表示是 1101 ,所以连续 1 的最大个数是 2。

解决方案:

#!/bin/python3

import sys


n = int(input().strip())
result = []
counter = 1
def get_binary(num):
    if num == 1:
        result.append(num)
        adj(result)
    else:
        result.append(num%2)
        get_binary(int(num/2))

def adj(arr):
    global counter
    for x in range(0,len(arr)-1):
        if arr[x] == 1 and (arr[x] == arr[x+1]):
            counter += 1
    print(counter)

get_binary(n)

它没有通过所有示例测试用例。我做错了什么?

【问题讨论】:

  • 试试 115。你会得到 5,你需要 3。你正在计算 所有 1 的数组,而你必须保留最长的一个。
  • 什么情况下不通过?在这些情况下它会做什么?请按照发布指南的要求展示这些内容。
  • 这与您的测试用例无关,但您的二进制文件是向后的
  • @Jean-FrançoisFabre 我用这个代码得到 4。
  • 哦,那是因为最后一个 1s 字符串计数错误。 4确实。双重错误。

标签: python


【解决方案1】:

下面是一个可以工作的简化版本

def func(num):
  return max(map(len, bin(num)[2:].split('0')))
  • 将整数转换为二进制表示bin(num)

  • 从二进制表示bin(num)[:2]中去除0b

  • 在字符 0 处拆分字符串 bin(num)[2:].split('0')

  • 找到最大长度的字符串并返回数字

【讨论】:

  • @Jean-FrançoisFabre 我用解释更新了答案
  • 我更喜欢这样。我现在没有赞成票(不是开玩笑)。您可以尝试用简单的len 更改lambda 吗?会更清楚。
  • @Jean-FrançoisFabre 完成!谢谢你的想法.. :)
  • 现在您的帖子开始看起来不错了 :) 那些二进制操作问题总是以转换为二进制字符串和操作字符串而告终。这总是让我很沮丧,因为我想用位移来做所有事情......
  • 顺便说一句,我忍不住编辑您的答案以添加return 声明:)
【解决方案2】:

这是使用regex 的替代解决方案:

>>> import re
>>> def bn(i):
...     n = bin(i)[2:]
...     return n,max(len(j) for j in re.findall(r'1+', n))
...
>>>
>>> bn(13)
('1101', 2)
>>> bn(25)
('11001', 2)

【讨论】:

    【解决方案3】:

    您的计数器逻辑在几个方面是不正确的,M. Fabre 确定了主要的一个。结果是计算所有序列组合中后续 1 的总数,并从 counter 的初始值加 1。 rogue-one 给了你一个可爱的 Pythonic 解决方案。要在您的使用级别修复此问题,请进入 adj 并修复...

    1. 不要在函数外使用counter;保持本地化。
    2. 创建第二个变量,它是您迄今为止找到的最佳字符串。
    3. 对当前字符串使用counter;当您达到 0 时,与目前最好的比较,重置计数器,然后继续。\

    中心逻辑类似于...

    best = 0
    counter = 0
    for bit in arr:
        if bit == 1:
            counter += 1
        else:
            if counter > best:
                best = counter
            counter = 0
    
    # After this loop, make one last check, in case you were on the longest
    #   run of 1s when you hit the end of the bits.
    # I'll leave that coding to you.
    

    【讨论】:

      【解决方案4】:

      这里有一些聪明的答案,我想我会使用传统的有效命令式方法添加一个替代方案。

      此方法首先将数字转换为字符串二进制表示。从那里它更新一堆最长的值,并检查是否有更长的值要添加。因此,您最终会得到一堆按最长连续 1 排序的值。要选择最大值,只需从堆栈中pop()

      def longest_consecutive_one(n):
          stack = [0]
          counter = 0
          binary_num = '{0:08b}'.format(n)
          length = len(binary_num) - 1
          for index, character in enumerate(binary_num):
              if character == "1":
                  counter += 1
              if character == '0' or index == length:
                  if stack[-1] < counter:
                      stack.append(counter)
                      counter = 0
          return stack.pop()
      

      样本输出:

      >>> longest_consecutive_one(190)
      5
      >>> longest_consecutive_one(10)
      1
      >>> longest_consecutive_one(10240)
      1
      >>> longest_consecutive_one(210231)
      6
      

      【讨论】:

        【解决方案5】:

        以下编写代码的输出将给出输入十进制数中连续一个的最大数量。

            n = int(raw_input().strip())
            num = list((bin(n).split('b'))[1])
            num.insert(0,'0')
            num.append('0')
            count = 0
            store = 0
            for i in range(0,len(num)):
                if ((num[i]) == '1'):
                    count+=1
                elif ('0' == (num[i])) and count !=0:
                    if count >= store:
                        store = count
                    count = 0
            print store
        

        【讨论】:

          【解决方案6】:

          这个使用了位魔法

          def maxConsecutiveOnes(x): 
          
              # Initialize result 
              count = 0
          
              # Count the number of iterations to 
              # reach x = 0. 
              while (x!=0): 
          
                  # This operation reduces length 
                  # of every sequence of 1s by one. 
                  x = (x & (x << 1)) 
          
                  count=count+1
          
              return count 
          
          # Driver code 
          print(maxConsecutiveOnes(14)) 
          print(maxConsecutiveOnes(222))
          

          输出将是 3 和 4

          【讨论】:

            【解决方案7】:
            #include<bits/stdc++.h>
            using namespace std;
            int main()
            {
                int n;
                int count=0,min=0;
                cin>>n;
                for(int i=0;n>0;i++)
                {
                    if(n%2==1)
                            {
            
                            count++;
                              if(count>min)
                               {
                                 min=count;
            
                               }
                            }
                        else
                            {
                             count=0;
                             }
                    n = n/2;
            
                }
                   cout<<min<<endl;
                return 0;
            }
            

            【讨论】:

            • 语言是 python,不是 C++。
            【解决方案8】:

            我认为第一个答案是最好的。我以类似的方式完成了它,可能更容易理解。

            import sys
            if __name__ == '__main__':
                n = int(input())
                bina=str(format(n,'b'))
                holder=bina.split('0')
                max_num = max(holder,key=len)
                print(len(max_num))
                
            

            【讨论】:

              【解决方案9】:

              你可以使用LoopList解决这个问题,如下图:

              def maxConsecutive(n):
                binary = format(n,'b')
                print(f"The Binary Represntation of the number {n} is = {binary}")
                length = len(binary)
                count =0 #Create a Counter Variable to Count the Number of 1's
                
                #Create a blank Array to store the values of number of Consecutive 1's:
                Store = [] 
              
                for i in range(length):
                  #Check if the number is 1,if yes increase the value of counter variable
                  if (binary[i]=='1'):
                    count+=1
              
                  #Check if the number is 0 or last digit of the binary number:
                  #to store the value of counter in the list and set the counter variable to 0
                  if (binary[i]=='0' or i == length-1):
                    if (count!=0): #To not add count=0 in the List
                      Store.append(count)
                    count = 0
              
                print("The List of Number of Consecutive 1's is : ",Store)
                print("The Maximum Number of consecutive 1 is: ",max(Store))
              
              #Driver Code:  
              n = int(input("Enter the Number: "))
              maxConsecutive(n)
              

              【讨论】:

                猜你喜欢
                • 2017-01-03
                • 1970-01-01
                • 2012-02-23
                • 1970-01-01
                • 2016-12-25
                • 2023-03-27
                • 1970-01-01
                • 2014-05-01
                • 1970-01-01
                相关资源
                最近更新 更多