[Bit Operations-Simple] Interview Questions 05.03. Flip the Digits

[Title]
Given a 32-bit integer num, you can change a digit from 0 to 1. Please write a program to find the length of the longest string of 1s you can get.
[Example 1]
Input: num = 1775(110111011112)
Output: 8
[Example 2]
Input: num = 7(01112)
Output: 4
[Code]
[Python]
Insert picture description here

class Solution:
    def reverseBits(self, num: int) -> int:
        if num<0:
            temp=bin(num)[3:]
            s=list("{0:1>32}".format(temp))
            i=31
            for i in range(31,31-len(temp),-1):
                s[i]='0' if s[i]=='1' else '1'
            num=int("".join(s),2)+1
        num_s=list(bin(num)[2:]+"0")
        pos=[]
        cnt=0
        for index,c in enumerate(num_s):
            if c=='0':
                pos.append([index-1,cnt])
                cnt=0
            else:
                cnt+=1
        if len(pos)==1:
            print(num)
            if len(num_s)<=33:
                return min(pos[0][1]+1,32)
            else:
                return pos[0][1]
        maxlen=0
        for i in range(1,len(pos)):
            if (pos[i][0]-pos[i][1]-1)==pos[i-1][0]:
                maxlen=max(maxlen,pos[i][1]+pos[i-1][1]+1)
        return maxlen

[Method 2: Double pointer]
Insert picture description here

class Solution:
    def reverseBits(self, num: int) -> int:
        pre, cur =0, 0
        res = 1
        for i in range(32):
            if num & (1<<i):
                cur+=1
            else:
                res=max(res, pre+cur)
                pre = cur +1
                cur = 0
        res=max(res, pre+cur)
        return res

Guess you like

Origin blog.csdn.net/kz_java/article/details/115265883