양수와 비트 범위가 주어집니다. 우리의 임무는 범위에서 설정되지 않은 비트를 계산하는 것입니다.
Input : n = 50, starting address = 2, ending address = 5 Output : 2
2 ~ 5 범위에 '2' 설정되지 않은 비트가 있습니다.
알고리즘
Step 1 : convert n into its binary using bin(). Step 2 : remove first two characters. Step 3 : reverse string. Step 4 : count all unset bit '0' starting from index l-1 to r, where r is exclusive.
예시 코드
# Function to count unset bits in a range def countunsetbits(n,st,ed): # convert n into it's binary bi = bin(n) # remove first two characters bi = bi[2:] # reverse string bi = bi[-1::-1] # count all unset bit '0' starting from index l-1 # to r, where r is exclusive print (len([bi[i] for i in range(st-1,ed) if bi[i]=='0'])) # Driver program if __name__ == "__main__": n=int(input("Enter The Positive Number ::>")) st=int(input("Enter Starting Position")) ed=int(input("Enter Ending Position")) countunsetbits(n,st,ed)
출력
Enter The Positive Number ::> 50 Enter Starting Position2 Enter Ending Position5 2