题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
def check_ip(ip):
lst = ip.split('.')
if len(lst) != 4:
return False
for i in lst:
if not i.isdigit():
return False
if int(i) not in range(0, 256):
return False
return True
def check_mask(mask):
lst = mask.split('.')
if len(lst) != 4:
return False
bstr = ''
for i in lst:
if not i.isdigit():
return False
if int(i) not in range(0, 256):
return False
temp = bin(int(i)).replace('0b', '')
bstr += (8-len(temp)) * '0' + temp
if '0' not in bstr or '1' not in bstr or '01' in bstr:
return False
return True
def check_sub(ip1, ip2, mask):
lst1, lst2, lst_mask = ip1.split('.'), ip2.split('.'), mask.split('.')
for i in range(4):
n1, n2, m = int(lst1[i]), int(lst2[i]), int(lst_mask[i])
if n1 & m != n2 & m:
return False
return True
while True:
try:
mask, ip1, ip2 = input(), input(), input()
if check_ip(ip1) and check_ip(ip2) and check_mask(mask):
if check_sub(ip1, ip2, mask):
print(0)
else:
print(2)
else:
print(1)
except:
break