题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
import sys def ipgood(ip): iplist = ip.split('.') if len(iplist)!=4 : return False twostr = '' for i in iplist: if not i.isdigit(): return False if int(i)>255 or int(i)<0: return False intwo = bin(int(i))[2:] twostr += intwo.zfill(8) return twostr def maskgood(mask): masklist = mask.split('.') if len(masklist)!=4: return False twostr = '' for i in masklist: if not i.isdigit(): return False if int(i)>255 or int(i)<0: return False intwo = bin(int(i))[2:] twostr += intwo.zfill(8) is_one=1 if twostr[0]==0: return False for i in twostr: if i=='0': is_one=0 if is_one==0 and i=='1': return False if is_one: return False return twostr mask = input().strip() ip1 = input().strip() ip2 = input().strip() ip1 = ipgood(ip1) ip2 = ipgood(ip2) mask = maskgood(mask) if not (ip1 and ip2 and mask): print('1') else: ip1 = int('0b'+ip1,2) ip2 = int('0b'+ip2,2) mask = int('0b'+mask,2) maip1 = mask&ip1 maip2 = mask&ip2 if maip1 == maip2: print('0') else: print(2)