题解 | #整数与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))

解题思路在代码注释里面

基本就是位运算思路了

没整明白,这也算中等题

全部评论

相关推荐

07-31 14:17
门头沟学院 Java
牛客39712426...:那他今年招集贸呢,26届本科大部分不就是属猴,除非写明招25的或者研究生
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务