题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
while True:
try:
subnet = list(map(int, input().split(".")))
net1 = list(map(int, input().split(".")))
net2 = list(map(int, input().split(".")))
temp = []
def IPChange(ip):
subnet_b = ""
for i in ip:
if i > 255 or i < 0:
return 1
else:
subnet_b1 = format(i, "b").rjust(8, "0")
subnet_b = subnet_b + subnet_b1
return subnet_b
subnetChange = IPChange(subnet)
net1Change = IPChange(net1)
net2Change = IPChange(net2)
ipresult1 = ""
ipresult2 = ""
if (
subnetChange == 1
or net1Change == 1
or net2Change == 1
or subnetChange[:8] != "11111111"
or subnetChange[-8:] != "00000000"
):
print(1)
else:
for n in range(len(subnetChange)):
if subnetChange[n] == "1" and net1Change[n] == "1":
ipresult1 = ipresult1 + "1"
else:
ipresult1 = ipresult1 + "0"
for n in range(len(subnetChange)):
if subnetChange[n] == "1" and net2Change[n] == "1":
ipresult2 = ipresult2 + "1"
else:
ipresult2 = ipresult2 + "0"
if ipresult1 == ipresult2:
print(0)
else:
print(2)
except:
break
查看20道真题和解析