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

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

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

def check_ip(s):
    ip_list = list(map(int, s))
    if len(ip_list) != 4 or max(ip_list) > 255 or min(ip_list) < 0:
        return False
    return True


while True:
    try:
        valid = True 
        x = input().split(".")
        y = input().split(".")
        z = input().split(".")

        valid = valid and check_ip(x) and check_ip(y) and check_ip(z) # 验证ip合法

        bin_list = [(bin(int(xx))).replace("0b", "").rjust(8, "0") for xx in x] # 不添加rjust则1.255.255.0合法
        mask = "".join(bin_list)
        valid = valid and (mask.rfind("1") + 1) == mask.find("0") # 验证掩码

        m, n = [], []
        if not valid:
            print("1")
        else:
            for i in range(len(x)):
                m.append(int(x[i]) & int(y[i]))
                n.append(int(x[i]) & int(z[i]))
            print("0" if m == n else "2")
    except:
        break

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务