1. 题目
www.nowcoder.com/practice/66…
2. 考点
- 进制转换 二进制与十进制 相互转换 可使用函数
bin() int(x,base=2) 可手写进制转换函数
- 字符串的切割以及缺失填补。
3. 解析
- 分析字符串的规律 都使用八位进行存储。
- 字符与数字之间的相互转换。
- 采用bin() int()函数进行解析进制。
- 字符串拼接时需要考虑好长度
hc(x) 可使用 bin(x)[2:]进行替换
4. 核心代码
def hc(d: int):
ret = []
while True:
n = d % 2
ret.insert(0, str(n))
if d == 0: break
d //= 2
return ret
def to_ip_int(i: str):
i_list = [int(j) for j in i.split('.')]
result = []
for j in i_list:
h = hc(j)
tmp = "0" * (8 - len(h)) + "".join(h) if len(h) < 8 else "".join(h[-8:])
result.append(tmp)
return int("".join(result), base=2)
def to_ip_str(i: int):
h = hc(i)
result = "0" * (8 * 4 - len(h)) + "".join(h) if len(h) < 32 else "".join(h[-8 * 4:])
result = [str(int(result[i:i + 8], base=2)) for i in range(0, len(result), 8)]
return ".".join(result)
def bp(i):
if isinstance(i, str):
return to_ip_int(i)
if isinstance(i, int):
return to_ip_str(i)
if __name__ == '__main__':
while True:
try:
print(bp(input()))
print(bp(int(input())))
except EOFError:
break