题解 | #判断两个IP是否属于同一子网 & 按位与运算符
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
''' & 按位与运算符: 参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0 a=60 a1 = bin(60)[2:].zfill(8) b=13 b1 = bin(13)[2:].zfill(8) print(a1) print(b1) print(bin(a&b)[2:].zfill(8)) ''' # 先判断ip mask是否合法 def iflegal_ip(ip): if len(ip)!=4: return False else: for i in ip: if ( i.isdigit()==0 or i=='' or int(i)>255 or int(i)<0 or (i[0]=='0' and len(i)>1) ): return False break else: return True def iflegal_mask(mask): if iflegal_ip(mask)==0: return False else: mask_0b='' for i in mask: i_bin=bin(int(i))[2:].zfill(8) mask_0b += i_bin #print(mask_0b) rfind_1=mask_0b.rfind('1') find_0=mask_0b.find('0') if find_0-rfind_1==1: return True else: return False def ifsame_subnet(mask,ip1,ip2): new_ip1='' new_ip2='' for i in range(4): i_bin1=bin(int(mask[i])&int(ip1[i]))[2:].zfill(8) i_bin2=bin(int(mask[i])&int(ip2[i]))[2:].zfill(8) new_ip1 += i_bin1 new_ip2 += i_bin2 if new_ip1==new_ip2: return True else: return False while 1: try: mask=list(input().split('.')) ip1=list(input().split('.')) ip2=list(input().split('.')) #print(mask,iflegal_mask(mask)) #print(ip1,iflegal_ip(ip1)) #print(ip2,iflegal_ip(ip2)) if ( iflegal_mask(mask)==0 or iflegal_ip(ip1)==0 or iflegal_ip(ip2)==0 ): print(1) else: if ifsame_subnet(mask,ip1,ip2): print(0) else: print(2) except: break