题解 | #判断两个IP是否属于同一子网#

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

https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218

def checkip(ip):
    """判读是否为IP的函数"""
    if len(ip) != 4:
        return False
    flag = 0
    for sec in ip:
        if 0 <= int(sec) <= 255 and sec == str(int(sec)):
            flag += 1
    return flag == 4


def checksub(submask):
    '''进一步判断是否为掩码的函数'''
    tem = ''
    for sec in submask:
        tem += bin(int(sec))[2:].rjust(8, "0")
    if tem[0] == 0 or tem[-1] == 1:
        return False
    p = tem.find("0")
    if "1" in tem[p:]:
        return False
    return True


def check(ip1, ip2, submask):
    """判读两ip是否为同一子网的函数"""
    if not checkip(submask) or not checksub(submask) or not checkip(ip1) or not checkip(ip2):
        return 1
    lsub = []
    lip1, lip2 = [], []
    tmp1, tmp2 = '', ''
    for i in range(4):
        lsub.append(bin(int(submask[i]))[2:].rjust(8, "0"))
        lip1.append(bin(int(ip1[i]))[2:].rjust(8, "0"))
        lip2.append(bin(int(ip2[i]))[2:].rjust(8, "0"))
    for j in range(4):
        for k in range(8):
            tmp1 += str(int(lip1[j][k]) and int(lsub[j][k]))
            tmp2 += str(int(lip2[j][k]) and int(lsub[j][k]))
    if tmp1 == tmp2:
        return 0
    else:
        return 2


while True:
    try:
        submask = input().split(".")
        ip1 = input().split(".")
        ip2 = input().split(".")
        print(check(ip1, ip2, submask))
    except:
        break

全部评论

相关推荐

牛客722552937号:新锐之星有点坑爹,特别是对男的
点赞 评论 收藏
分享
shtdbb_:还不错,没有让你做了笔试再挂你
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务