题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
import sys ''' 性能最好应该是位运算 先找8个1 然后每次跟这8个1相与之后 往后这个数字就往右移8位 ''' def to_address(i): b = (1 << 8) - 1 result = '' n = int(i) for t in range(4): result = str(n & b) if t == 0 else f'{str(n & b)}.{result}' n >>= 8 return result ''' 同理 拆分了之后 每次累加往左移8位即可 ''' def to_digit(s): a = s.split('.') result = 0 for i in a: result = result << 8 result += int(i) return result for line in sys.stdin: i = line.strip() if i.isdigit(): print(to_address(i)) else: print(to_digit(i))
解题思路在代码注释里面
基本就是位运算思路了
没整明白,这也算中等题