题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
mask_ip = [int(i) for i in input().split('.')] ip1 = [int(i) for i in input().split('.')] ip2 = [int(i) for i in input().split('.')] flag = 0 for i in mask_ip + ip1 + ip2: if i < 0 or i > 255: flag = 1 break if flag != 1: # 先判断子网掩码是否合法 mask_ip1 = ['0'*(8-len(bin(i)[2:]))+bin(i)[2:] for i in mask_ip] mask_ip2 = ''.join(mask_ip1) if set(mask_ip2) in ({'0'},{'1'}) or '01' in mask_ip2: flag = 1 else: for i in range(4): if ip1[i]&mask_ip[i] != ip2[i]&mask_ip[i]:flag = 2 print(flag)