题解 | #判断两个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

全部评论

相关推荐

头像
05-14 12:29
安卓
点赞 评论 收藏
转发
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务