HJ39 判断两个IP是否属于同一子网

HJ39 判断两个IP是否属于同一子网

这道题是华为2019年暑假实习生机考的一道题,这两天在网上找到的,不得不说,必须得在牛客网上多l联系一下编程环境,这道题,需要注意的有一下几点:需要单独判断一下子网掩码,因为它的首和尾都有特殊规定必须是255和0,需要计算ip地址和子网掩码的与结果,与结果只有十进制可以算,所以需要将计算后的结果转换为二进制 bin(a&b),并且输入的时候,需要按照以下形式

while True:
	try:
		输入1 = input()
		输入2 = input()
		输入3 = input()
		...
	except:
		break
def judge(ip):
    # 将字符串变为int列表
    iplist = [int(num) for num in ip.split(".")]
    for num in iplist:
        if num<0 or num>255 :
            return 1
def judge_son(ip):
    iplist = [int(num) for num in ip.split(".")]
    if iplist[0]!= 255 or iplist[-1]!=0:
        return 1
    for num in iplist:
        if num<0 or num>255 :
            return 1
def ipAndSon(ip,son):
    # 计算ip地址与子网掩码之间的AND计算
    iplist = [int(num) for num in ip.split(".")]
    sonlist = [int(num) for num in son.split(".")]
    res = []
    for i in range(4):
        res.append(bin(iplist[i]&sonlist[i]))
    return res
def judgeSameList(list1,list2):
    for i in range(len(list1)):
        if list1[i]==list2[i]:
            pass
        else:
            return False
    return True
while True:
    try:
        son_net = input()
        ip1 = input()
        ip2 = input()
        if judge_son(son_net)==1 or judge(ip1)==1 or judge(ip2)==1:
            print(1)
        else:
            res1 = ipAndSon(ip1,son_net)
            res2 = ipAndSon(ip2, son_net)
            if judgeSameList(res1, res2):
                print(0)
            else:
                print(2)
    except:
        break

你可能感兴趣的:(leetcode,python,tcp/ip,网络协议,网络)