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

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

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

import re
zto2525 = r'(\d|1?\d\d|2[0-4]\d|25[0-5])' #0-255的匹配
pattern = r'^' + zto2525 + r'\.' + zto2525 + r'\.' + zto2525 + r'\.' + zto2525 + r'$'#匹配有效掩码和IP地址的格式
pattern_yanma = r'^(1+0+|1+|0+)$' #匹配掩码是否为全1或全0或先1后0组成

#判断掩码是否为全1或全0或先1后0组成
def is_1_0(yanma):
    lst = yanma.split('.')
    res = ''
    for l in lst:
        res += str(bin(int(l)))[2:].rjust(8, '0')
    if re.match(pattern_yanma, res):
        return True
    else:
        return False

# 处理两个IP地址和掩码的与操作 如果一样则返回True
def handle(yanma, IP1, IP2):
    lst_yanma = yanma.split('.')
    lst_IP1 = IP1.split('.')
    lst_IP2 = IP2.split('.')
    res1 = ''
    res2 = ''
    for i in range(len(lst_yanma)):
        res1 += str(int(lst_IP1[i]) & int(lst_yanma[i]))
        res2 += str(int(lst_IP2[i]) & int(lst_yanma[i]))
    if res1 == res2:
        return True
    else:
        return False

while True:
    try:
        yanma = input().strip()
        IP1 = input().strip()
        IP2 = input().strip()
        # 判断掩码或IP格式是否非法:
        if re.match(pattern, yanma) and re.match(pattern, IP1) and re.match(pattern, IP2) and is_1_0(yanma):
            if handle(yanma, IP1, IP2):
                print('0')
            else:
                print('2')
        else:
            print('1')
    except:
        break

全部评论

相关推荐

SadnessAlex:跟三十五岁原则一样,人太多给这些***惯坏了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务