题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
# 优秀解法 import sys def check(s): l = s.split('.') if len(l) != 4: return False for i in l: i = int(i) if 0> i or i > 255: return False return True def check_mask(s): l = s.split('.') r = '' for i in l: a = bin(int(i))[2:].rjust(8,'0') r+=a if r.find('0') < r.rfind('1'): return False else: return True def same(ip1,ip2,mask): l1 = ip1.split('.') l2 = ip2.split('.') l3 = mask.split('.') s1 = [] s2 = [] for i,j in zip(l1, l3): s1.append(int(i)&int(j)) for i,j in zip(l2, l3): s2.append(int(i)&int(j)) if s1 == s2: return True else: return False while True: try: mask = input().strip() ip1 = input().strip() ip2 = input().strip() if check(ip1) and check(ip2) and check(mask) and check_mask(mask): if same(ip1, ip2, mask): print('0') else: print('2') else: print('1') except: break