题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
```def checkip(lst):
for i in lst:
if int(i) < 0 or int(i) > 255:
return False
return True
def checkmask(lst):
i = changebin(lst)
if i[0] != '11111111' or i[-1] != '00000000':
return False
else:
return checkip(lst)
def changebin(lst):
res = []
for i in lst:
res.append(bin(int(i))[2:].rjust(8, '0'))
return res
def checksame(ip1_bin, ip2_bin, mask_bin):
count = 0
for i in range(4):
a = int(ip1_bin[i], 2) & int(mask_bin[i], 2)
b = int(ip2_bin[i], 2) & int(mask_bin[i], 2)
if a == b:
count += 1
if count == 4:
return True
else:
return False
while True:
try:
mask = input().split('.')
ip1 = input().split('.')
ip2 = input().split('.')
ip1_bin = []
ip2_bin = []
mask_bin = []
if checkmask(mask) and checkip(ip1) and checkip(ip2):
ip1_bin = changebin(ip1)
ip2_bin = changebin(ip2)
mask_bin = changebin(mask)
if checksame(ip1_bin, ip2_bin, mask_bin):
print('0')
else:
print('2')
else:
print('1')
except:
break