题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
mask = list(map(int,input().split('.')) ) ip1 = list(map(int,input().split('.')) ) ip2 = list(map(int,input().split('.')) ) def check_mask(m): if len(m) != 4: return (False,None) else: for i in m: if i<0 or i>255: return (False,None) int32 = m[0]*256**3 + m[1]*256**2 + m[2]*256 + m[3] strb = bin(int32)[2:] pos1 = strb.rfind('1') pos0 = strb.find('0') if pos0 - pos1 == 1: return (True,int32) else: return (False,None) def check_ip(ip): if len(ip) != 4: return (False,None) else: for i in ip: if i<0 or i>255: return (False,None) int32 = ip[0]*256**3 + ip[1]*256**2 + ip[2]*256 + ip[3] return (True,int32) ret = check_mask(mask) if not ret[0]: print(1) exit() ret1 = check_ip(ip1) if not ret1[0]: print(1) exit() ret2 = check_ip(ip2) if not ret2[0]: print(1) exit() if (ret[1] & ret1[1]) == (ret[1] & ret2[1]): print(0) else: print(2)
1.255.255.0
187.39.235.7
219.79.189.231
预期输出 1
实际输出 2