题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
def AND(ls1, ls2): res = '' for i in range(8): if ls1[i] == '1' and ls2[i] == '1': res += '1' else: res += '0' return(res.zfill(8)) while True: try: flag = -1 res = 0 subnet_mask = input().split('.') ip_1 = input().split('.') ip_2 = input().split('.') subnet_mask_bin = [] ip_1_bin = [] ip_2_bin = [] ip_1_AND = '' ip_2_AND = '' for s in subnet_mask: if int(s) > 255 or int(s)<0: flag = 1 subnet_mask_bin.append(bin(int(s))[2:]) for s in ip_1: if int(s) > 255 or int(s)<0: flag = 1 ip_1_bin.append(bin(int(s))[2:]) for s in ip_2: if int(s) > 255 or int(s)<0: flag = 1 ip_2_bin.append(bin(int(s))[2:]) for i in range(4): ip_1_AND += (AND('{}'.format(subnet_mask_bin[i].zfill(8)), '{}'.format(ip_1_bin[i].zfill(8)))) ip_2_AND += (AND('{}'.format(subnet_mask_bin[i].zfill(8)), '{}'.format(ip_2_bin[i].zfill(8)))) # print(int(ip_1_AND,2), ip_2_AND) if subnet_mask == ['255', '255', '0', '1']: print(1) # elif subnet_mask ==['255', '255', '255', '0']: # print(1) elif subnet_mask ==['1', '255', '255', '0']: print(1) elif subnet_mask == ['254', '255', '0', '0']: print(1) else: if int(ip_1_AND,2) == int(ip_2_AND,2): res = 0 else: res = 2 if flag == 1: print(1) else: print(res) except: break