题解 | #识别有效的IP地址和掩码并进行分类统计#

识别有效的IP地址和掩码并进行分类统计

https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682

jiance = [0] * 256
for jian in range(256):
    jiance[jian] = str(jian)


def hefa(a):
    global jiance
    for sb in a:
        if sb not in jiance:
            return False
    return True


def panduan(a):
    if a[0] == "1" and a[-1] == "0":
        k = 1
        for i in range(len(a) - 1):
            if a[i + 1] == "0" and a[i] == "1":
                k = k + 1
            elif a[i + 1] == "1" and a[i] == "0":
                k = k + 10
        if k == 2:
            return True
        else:
            return False
    else:
        return False


c = [0] * 7
while True:
    try:
        i = input()
        ip = i.split("~")[0]
        zw = i.split("~")[1]
        q = ip.split(".")
        p = zw.split(".")
        s = p
        p = list(map(lambda x: "0" * (8 - len(bin(int(x))[2:])) + bin(int(x))[2:], p))
        p = "".join(p)

        if hefa(q) and hefa(s):
            if int(q[0]) == 127 or int(q[0]) == 0:
                pass
            elif panduan(p):
                if int(q[0]) >= 1 and int(q[0]) <= 126:
                    c[0] += 1
                    if q[0] == "10":
                        c[6] += 1
                elif int(q[0]) >= 128 and int(q[0]) <= 191:
                    c[1] += 1
                    if q[0] == "172":
                        if int(q[1]) >= 16 and int(q[1]) <= 31:
                            c[6] += 1
                elif int(q[0]) >= 192 and int(q[0]) <= 223:
                    c[2] += 1
                    if q[0] == "192":
                        if q[1] == "168":
                            c[6] += 1
                elif int(q[0]) >= 224 and int(q[0]) <= 239:
                    c[3] += 1
                elif int(q[0]) >= 240 and int(q[0]) <= 255:
                    c[4] += 1
                elif int(q[0]) == 127 or int(q[0]) == 0:
                    c[5] -= 1
            elif not panduan(p):
                c[5] += 1
        else:
            c[5] += 1
    except:
        break
print(" ".join(list(map(str, c))))

将子网掩码转化成二进制以后是需要在前面补零补满8位的,一直没注意到这点卡了好久。。。

全部评论

相关推荐

03-29 12:10
门头沟学院 C++
挣K存W养DOG:散漫消极者淘汰,一眼坑爹。实习几个月转正的时候说你加班太少,能力还行态度不够积极裁了,马上老实。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务