给定一个32位整数 num,你可以将一个数位从0变为1。请编写一个程序,找出你能够获得的最长的一串1的长度。
示例 1:
输入: num = 1775(110111011112)
输出: 8
示例 2:
输入: num = 7(01112)
输出: 4
Python 解答:
1.耿直的方法
class Solution:
def reverseBits(self, num: int) -> int:
def transform(n):
n = ((1<<32)-1)&n
res = [0 for i in range(32)]
i = 0
while n > 0:
r = n&1
res[i] = r
n >>= 1
i += 1
return res
res = transform(num)
if sum(res) == 32:
return 32
max_value = 0
for i in range(len(res)):
if res[i] == 0:
temp = res[::]
temp[i] = 1
count = 0
for item in temp:
if item == 1:
count += 1
if count > max_value:
max_value = count
else:
count = 0
return max_value
2.单次遍历
class Solution:
def reverseBits(self, num: int) -> int:
n = ((1<<32)-1)&num
pre = 0
cur = 0
max_value = 1
while n > 0:
r = n&1
if r:
cur += 1
else:
if cur+pre+1 > max_value:
max_value = cur+pre+1
pre = cur
cur = 0
n >>= 1
else:
max_value = max(max_value, cur+1+pre)
return min(max_value, 32)
留言