题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
想得有点复杂了
def ip_change(string,i): if i == 0: # 将ip转化成普通数组 string = string.split('.') a = [] for i in string: # ip 一位数字二进制的最大长度是8,不足则用‘0’补齐 a.append('0'*(8-len(bin(int(i))[2:]))+bin(int(i))[2:]) b = int(''.join(i for i in a),2) return b if i == 1: bin1 = str(bin(int(string))[2:]) a = [] b = [] # 密码二进制默认32位,遍历时可以将其补齐 32 位 for i in range(len('0'*(32-len(bin1))+bin1)//8): a.append(bin1[::-1][i*8:(i+1)*8][::-1]) a = a[::-1] for i in a : b.append(int(i,2)) return '.'.join(str(i) for i in b ) for i in range(2): string = input().strip() print(ip_change(string,i))