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

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

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

def check_ip_or_mask(parts):
    # 检查IP地址或子网掩码的每个部分是否在0到255之间
    return all(0 <= int(p) <= 255 for p in parts)


def is_valid_mask(mask):
    # 将子网掩码转换为二进制字符串
    bin_mask = "".join(["{:08b}".format(int(part)) for part in mask])
    # 找到第一个0出现的位置
    first_zero_index = bin_mask.find("0")
    # 确保从第一个0之后不再出现1
    return "1" not in bin_mask[first_zero_index:]


while True:
    try:
        mask = input().split(".")
        ip1 = input().split(".")
        ip2 = input().split(".")

        if not (
            check_ip_or_mask(mask)
            and check_ip_or_mask(ip1)
            and check_ip_or_mask(ip2)
            and is_valid_mask(mask)
        ):
            print("1")
            continue

        def get_bin(intList):
            return "".join(["{:08b}".format(int(i)) for i in intList])

        def is_same_net(mask, ip1, ip2):
            bin_mask = int(get_bin(mask), 2)
            p1_net = int(get_bin(ip1), 2) & bin_mask
            p2_net = int(get_bin(ip2), 2) & bin_mask
            print(0 if p1_net == p2_net else 2)

        is_same_net(mask, ip1, ip2)
    except EOFError:
        break

全部评论

相关推荐

三分入剑:我觉得还是学历问题 如果你真的想要进大厂不想在小厂的话读个211得研究生吧 我感觉简历还没你好呢 我都实习了俩月了 我投了一百多份能投出20多份简历 能面试六七次 我们部门只招研究生了都 现在连9本都很难找到像样的大厂了 你又没打过rm这种 我觉得想要进步的话就考个研究生吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务