BOJ - 2064 - IP 주소

Updated:

import sys
def solution():
    N = int(input())
    ip = []
    for _ in range(N):
        ip.append(sys.stdin.readline().strip().split('.'))

    bitIP = []
    for i in range(N):
        temp = ""
        for j in range(4):
            binary = "{0:b}".format(int(ip[i][j]))
            while len(binary) != 8:
                binary = '0' + binary
            temp += binary
        bitIP.append(temp)

    networkAddress = ''
    for i in range(32):
        flag = False
        check = bitIP[0][i]
        for j in range(N):
            if check != bitIP[j][i]:
                flag = True
                break
        if flag: break
        else: networkAddress += check

    cnt = 0
    while len(networkAddress) != 32:
        networkAddress += '0'
        cnt += 1

    maskAddress = ''
    for i in range(32 - cnt):
        maskAddress += '1'
    for i in range(cnt):
        maskAddress += '0'

    ret = []
    for index in range(4):
        ret.append(int(networkAddress[index * 8 : index * 8 + 8], 2))

    print("{0}.{1}.{2}.{3}".format(ret[0], ret[1], ret[2], ret[3]))

    ret = []
    for index in range(4):
        ret.append(int(maskAddress[index * 8: index * 8 + 8], 2))

    print("{0}.{1}.{2}.{3}".format(ret[0], ret[1], ret[2], ret[3]))

solution()

https://www.acmicpc.net/problem/2064

Categories:

Updated:

Leave a comment