牛客华为机试HJ86
作者:互联网
1. 题目描述
2. Solution1
1、思路分析
把输入n转成bit字符串,然后用0切开,对剩余每一个只包含1的部分求长度并取长度最大值为最终结果。
2、代码实现
import sys
if sys.platform != "linux":
file_in = open("input/HJ86.txt")
sys.stdin = file_in
def solve(n):
n_bin = bin(n).replace("0b", "")
if '0' not in n_bin:
print(len(n_bin))
return
res = max(list(map(len, n_bin.split("0"))))
print(res)
for line in sys.stdin:
n = int(line.strip())
solve(n)
3. Solution 2
1、思路分析
取出n的每个bit上的值为cur_bit,若cur_bit为1,则当前最大值max_here自增1。不然,重置max_here为0。每遍历一位,取max_here与全局结果res的最大值保存到res,即res = max(max_here, res)。
2、代码实现
import sys
if sys.platform != "linux":
file_in = open("input/HJ86.txt")
sys.stdin = file_in
def solve(n):
res = 0
max_here = 0
for _ in range(32):
cur_bit = n & 1
n = n >> 1
max_here = 0 if cur_bit == 0 else max_here + 1
res = max(res, max_here)
print(res)
for line in sys.stdin:
n = int(line.strip())
solve(n)
标签:bin,max,here,sys,牛客,res,HJ86,机试,bit 来源: https://www.cnblogs.com/junstat/p/16177301.html