【问题标题】:Finding biggest binary gap寻找最大的二元差距
【发布时间】:2020-09-16 03:52:34
【问题描述】:

我必须找到一个整数的二进制间隙。

正整数 N 中的二进制间隙是在 N 的二进制表示中两端被 1 包围的连续零的任何最大序列。

例如:N = 1041 二进制:10000010001 结果:5(5 个零被 1 包围)

下面是我的代码,虽然 bin_no[22] 是 1 但它永远不会进入 if 语句。

def solution(N):
    bin_no = f'{N:32b}'
    print(len(bin_no))
    count = []

    for i in range(len(bin_no)):
        if bin_no[i] == 1:
            count[i] = 0
            j=i
            while(bin_no[j+1] != 1):
                count[i] +=1
                j +=1
            print (count[i])

print(solution(529))

【问题讨论】:

  • 你混淆了数字和字符。比较 '1',而不是 1
  • 与您的要求有些相干,但请注意 Python 有一个内置函数 bin,用于将整数转换为二进制表示;这样,您不必用空格填充,并且可以将每个二进制数字转换为整数,以防您更喜欢与这些数字进行比较;就像for binary_digit in map(int, bin(529)[2:]) ... if binary_digit == 1 ...
  • 您将数字与字符进行比较。这是python中的一个很好的解决方案。 stackoverflow.com/questions/48951591/…

标签: python


【解决方案1】:

简单快速

def solution(N):
    binary = bin(N)[2:].strip("0").split("1")
    return max(len(x) for x in binary)

【讨论】:

    【解决方案2】:

    使用正则表达式:

    def solution(N):
        bin_no = f'{N:b}'
        pt= r"10+(?=1)"
        mtchs = re. findall(pt, bin_no)
        print(bin_no)
        print(mtchs)
        mx = max(mtchs,key=len)
        return mx.count('0')
    
    print(solution(401))
    

    输出:

    110010001

    ['100', '1000']

    3

    【讨论】:

      【解决方案3】:

      我有一个 Java 解决方案。

      class BinaryGap {
          public static void main (String args[])
          {
              BinaryGap binaryGap = new BinaryGap();
              int n = 261;
              System.out.println("Max count : "+binaryGap.binaryValue(n));
          }
          
          public int binaryValue(int N) {
              String binaryValue = Integer.toBinaryString(N);
              System.out.println("binaryValue : "+binaryValue);
              int maxZeroCount = 0;
              int zeroCount = 0;
              for (int i = 0, n = binaryValue.length(); i < n; i++) {
                  if(binaryValue.charAt(i) == '0') {
                      ++zeroCount;
                  } else {
                      if(zeroCount > maxZeroCount) {
                          maxZeroCount = zeroCount;
                      }
                      zeroCount = 0;
                  }
              }
              return maxZeroCount;
          }
      }
      

      【讨论】:

      • 欢迎来到 Stackoverflow,感谢您的努力。然而这个问题是一个 python 标记的问题,所以你的答案在技术上是题外话。尝试并提供一个解决方案来回答 python 中的问题。
      【解决方案4】:

      这是另一个有效的解决方案。希望它可以帮助你。您只需要在函数中传递任意数字,它将返回最长的二进制间隙。

      def Solution(num):
      
      n = int(num/2)
      bin_arr = []
      
      for i in range(0,n):
          if i == 0:
              n1 = int(num/2)
              bin_arr.append(num%2)
          else:
              bin_arr.append(n1%2)
              n1 = int(n1/2)
      
              if n1 == 0:
                  break
      
      print(bin_arr)
      result = ""
      count = 0
      count_arr = []
      
      for i in bin_arr:
          if result == "found":
              if i == 0:
                  count += 1
              else:
                  if count > 0:
                      count_arr.append(count)
                      count = 0
          if i == 1:
              result = 'found'
          else:
              pass
      
      if len(count_arr) == 0:
          return 0
      else:
          return max(count_arr)
      
      print(LongestBinaryGap(1130))  # Here you can pass any number.
      

      【讨论】:

        【解决方案5】:

        您可以用 '1' 分割零并将零组作为一个列表。找到最长的就完成了!

        def solution(N):
            bin = f'{N:b}'  # for 32-bit representation with leading zeroes use f'{N:#032b}'
            splitted = bin.split('1')
            m = max(splitted, key=len)
            return len(m)
        

        原来是这样的:

        1041 -> '10000010001' -> ['', '00000', '000', ''] -> '00000' -> 5
        

        如果是这种情况,可以轻松更改代码以忽略前导和尾随零组。

        【讨论】:

          【解决方案6】:

          f'{n:b}'支持python v3.6+

          def solution(N):
              return len(max(f'{n:b}'.strip('0').split('1')))
          
          1. 使用f'{n:b}'将数字转换为二进制。
          2. strip('0') 删除左右两边的所有零。
          3. 将字符串转换为零列表 ex:['00', '000']split('1')
          4. 使用max(list)获取列表中最大长度的元素。
          5. return len(element)返回元素的长度

          【讨论】:

          • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
          【解决方案7】:

          PHP 版本:

          function solution($N) {
          $binary = decbin($N);
          $array_binary = array_map('intval', str_split($binary));
          $counter_gaps = 0;
          $longest = 0;
          
          foreach($array_binary as $key => $value){
              if($value == 1 && $key > 1){
                  $longest = $counter_gaps > 0 && $counter_gaps > $longest ? $counter_gaps : $longest;
                  $counter_gaps = 0;
              }else if($value == 0 && $key >= 1){
                  $counter_gaps++;
              }
          }
          return $longest; 
          

          }

          print_r(解决方案($N));

          【讨论】:

            猜你喜欢
            • 2017-08-03
            • 1970-01-01
            • 2015-08-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-01-15
            • 1970-01-01
            相关资源
            最近更新 更多