Python程序计算范围内的未设置位。
给定一个正数和位的范围。我们的任务是计算范围内的未设置位。
Input : n = 50, starting address = 2, ending address = 5 Output : 2
有2个未设置的位,范围为2到5。
算法
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
热门推荐
7 带清的简短祝福语
10 宝宝生日祝福语大全简短
11 发廊元旦祝福语大全简短
12 中秋送健康祝福语简短
13 外婆祝福语短句唯美简短
14 新婚贺词简短的祝福语
15 别人过大寿祝福语简短
16 长辈生日祝福语简短女性
17 祝福语大全简短6个
18 入学祝福语简短走心