题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
def check_ip(ip): ip_s = ip.split('.') if len(ip_s) != 4: return False else: for i in ip_s: if int(i) < 0 or int(i) > 255: return False return True def check_mask(mask): if not check_ip(mask): return False elif mask in ["255.255.255.255.255", "0.0.0.0"]: # 不用判断吗 我看咋都不判断 return False else: mask_s = mask.split('.') temp_bin = "".join([bin(int(i))[2:].rjust(8,'0') for i in mask_s]) index = temp_bin.index('0') # if temp_bin[index:].count('1') > 0: # return False if temp_bin.find('01') != -1: return False return True while True: try: mask,ip1,ip2 = input(),input(),input() out = 1 if not check_mask(mask) or not check_ip(ip1) or not check_ip(ip2): out = 1 else: num_mask = list(map(int,mask.split('.'))) num_ip1 = list(map(int,ip1.split('.'))) num_ip2 = list(map(int,ip2.split('.'))) res1 = [num_mask[i] & num_ip1[i] for i in range(4)] res2 = [num_mask[i] & num_ip2[i] for i in range(4)] out = 0 if res1 == res2 else 2 print(out) except: break