Python程序:查找n的二进制形式中连续1的最长长度


假设我们有一个非负值n,我们需要找到其二进制表示中连续1的最长长度。

例如,如果输入n = 1469,则输出为4,因为156的二进制表示为“10110111101”,所以有四个连续的1。

为了解决这个问题,我们将遵循以下步骤:

  • count := 0
  • 当n不等于0时,执行以下操作:
    • n := n AND (n左移一位)
    • count := count + 1
  • 返回count

示例

让我们来看下面的实现,以便更好地理解:

Open Compiler
def solve(n): count = 0 while n != 0: n = n & (n << 1) count = count + 1 return count n = 1469 print(solve(n))

输入

1469

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

4

更新于:2021年10月19日

618 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告