Python映射|给定整数二进制表示中最长连续1的长度

给定一个数n,求其二进制表示中最长连续1的长度。

null

例如:

Input : n = 14
Output : 3
The binary representation of 14 is 1110.

Input : n = 222
Output : 4
The binary representation of 222 is 11011110.

我们有解决这个问题的现有方案,请参考 二进制表示法中最长连续1的长度 链接我们可以用python快速解决这个问题。方法很简单,

  1. 使用 bin() 函数并删除开头的两个字符“0b”,因为 bin() 函数以字符串形式返回数字的二进制表示形式,并附加“0b”作为前缀。
  2. 使用以下命令分隔由零分隔的连续1的所有子字符串: split() 字符串的方法。
  3. 打印1的拆分子字符串的最大长度。

# Function to find Length of the Longest Consecutive
# 1's in Binary Representation
def maxConsecutive1( input ):
# convert number into it's binary
input = bin ( input )
# remove first two characters of output string
input = input [ 2 :]
# input.split('0') --> splits all sub-strings of
# consecutive 1's separated by 0's, output will
# be like ['11','1111']
# map(len,input.split('0'))  --> map function maps
# len function on each sub-string of consecutive 1's
# max() returns maximum element from a list
print ( max ( map ( len , input .split( '0' ))))
# Driver program
if __name__ = = '__main__' :
input = 222
maxConsecutive1( input )


输出:

4
© 版权声明
THE END
喜欢就支持一下吧
点赞10 分享