题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
10进制转换2进制
def decimalTobinary(decimal,binary_nu): # decimal: 10进制int # binary_nu: 二进制位数 '10进制转换2进制' binary = "" # 初始化二进制数为空字符串 while decimal > 0: # 当十进制数大于0时 remainder = decimal % 2 # 计算余数 binary = str(remainder) + binary # 将余数添加到二进制数的最前面 decimal = decimal // 2 # 更新十进制数为商 binary = (binary_nu - len(binary))*'0' + binary return binary
2进制转换10进制
def binaryTodecimal(binary): # binary, str '2进制转换10进制' decimal = 0 for i in range(len(binary)): decimal += int(binary[i]) * 2**(len(binary)-i-1) return decimal
整数与IP地址间的转换
import sys def binaryTodecimal(binary): '2进制转换10进制' # binary, str decimal = 0 for i in range(len(binary)): decimal += int(binary[i]) * 2**(len(binary)-i-1) return decimal def decimalTobinary(decimal,binary_nu): # decimal: 10进制int # binary_nu: 二进制位数 '10进制转换2进制' binary = "" # 初始化二进制数为空字符串 while decimal > 0: # 当十进制数大于0时 remainder = decimal % 2 # 计算余数 binary = str(remainder) + binary # 将余数添加到二进制数的最前面 decimal = decimal // 2 # 更新十进制数为商 binary = (binary_nu - len(binary))*'0' + binary return binary def ip_int(s): 'ip 转换10进制' digit_ele = [int(i) for i in s.split('.')] all_binary = "" for decimal in digit_ele: # 10进制转换2进制 binary = decimalTobinary(decimal, 8) all_binary += binary # 2进制转换10进制 return binaryTodecimal(all_binary) def int_ip(decimal): '10进制转换ip' # 10进制转换2进制 all_binary = decimalTobinary(decimal, 32) ips = [] for i in range(0,3*8+1,8): ips.append(binaryTodecimal(all_binary[i:i+8])) return '.'.join([str(i) for i in ips]) for line in sys.stdin: s = line[:-1] if '.'in s: print(ip_int(s)) else: print(int_ip(int(s)))