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

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

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

def ip_illegal(ip):
    ip = ip.split('.')
    for item in ip:
        if not 0 <= int(item) <= 255:
            return True
    return False


def y_illegal(y):
    y1 = y.split('.')
    for item in y1:
        if not 0 <= int(item) <= 255:
            return True
    y_bin = to_bin(y)
    a = y_bin.find('0')
    b = y_bin.rfind('1')
    if y_bin.find('0') != y_bin.rfind('1') + 1:
        return True
    return False


def to_bin(ip):
    ip1 = ip.split('.')
    list_temp = []
    for item in ip1:
        list_temp.append(bin(int(item))[2:].zfill(8))
    return ''.join(list_temp)


def calcu_and(y, ip):
    y_bin = to_bin(y)
    ip_bin = to_bin(ip)
    c = ''
    for item1, item2 in zip(y_bin, ip_bin):
        c += str(int(item1) and int(item2))
    return c


while True:
    try:
        y_code = input()
        ip_1 = input()
        ip_2 = input()
        if y_illegal(y_code) or ip_illegal(ip_1) or ip_illegal(ip_2):
            print(1)
        else:
            a = calcu_and(y_code, ip_1)
            b = calcu_and(y_code, ip_2)
            if calcu_and(y_code, ip_1) == calcu_and(y_code, ip_2):
                print(0)
            else:
                print(2)
    except:
        break

全部评论

相关推荐

11-01 08:48
门头沟学院 C++
伤心的候选人在吵架:佬你不要的,能不能拿户口本证明过户给我。。球球了
点赞 评论 收藏
分享
1 收藏 评论
分享
牛客网
牛客企业服务