题解 | #整数与IP地址间的转换#

整数与IP地址间的转换

https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea

湖边嗯造!

originalIp = str(input()).split('.')
originalNum = int(input())



newIpBinStr = ""
tmpIpBinList = list()
for thisNumStr in originalIp:
    thisNumInt = int(thisNumStr)

    while thisNumInt != 0:
        tmpIpBinList.append('1' if thisNumInt % 2 == 1 else '0')
        thisNumInt //= 2

    tmpIpBinList.reverse()

    if len(tmpIpBinList) < 8:
        tmpIpBinList = ['0'] * (8 - len(tmpIpBinList)) + tmpIpBinList

    newIpBinStr += ''.join(_ for _ in tmpIpBinList)

    tmpIpBinList.clear()
    
newIpBinList = [_ for _ in newIpBinStr]
newIpBinList.reverse()
newIpDecNum = 0
tmpBinTimes = 0
for i in range(len(newIpBinList)):
    if newIpBinList[i] == '1':
        newIpDecNum += 2 ** tmpBinTimes
    tmpBinTimes += 1



newNumBinStr = ""
tmpNumBinList = list()
while originalNum != 0:
    tmpNumBinList.append('1' if originalNum % 2 == 1 else '0')
    originalNum //= 2

tmpNumBinList.reverse()

if len(tmpNumBinList) < 32:
    tmpNumBinList = ['0'] * (32 - len(tmpNumBinList)) + tmpNumBinList

tmpNumBinList.reverse()
tmpNumBinList = [''] + tmpNumBinList

newDecIpStr = ""
tmpDecInt = 0
tmpBinTimes1 = 0
for i in range(1, len(tmpNumBinList) + 1):
    if tmpNumBinList[i] == '1':
        tmpDecInt += 2 ** tmpBinTimes1
    tmpBinTimes1 += 1

    if i % 8 == 0:
        newDecIpStr = ('.' if i < len(tmpNumBinList) - 1 else '') + str(tmpDecInt) + newDecIpStr
        tmpDecInt = 0
        tmpBinTimes1 = 0

    if i == len(tmpNumBinList) - 1:
        break



print(newIpDecNum)
print(newDecIpStr)

全部评论

相关推荐

zhiyog:哈哈哈哈哈哈哈哈哈哈哈哈哈
点赞 评论 收藏
分享
晗江雪:其实我只是觉得你们导员说的很好笑
点赞 评论 收藏
分享
07-03 11:02
中山大学 C++
字节刚oc,但距离九月秋招很近了有两段互联网实习,非腾讯字节。不敢赌转正,现在在纠结去还是不去如果实习俩月离职会有什么后果吗
阿城我会做到的:不去后悔一辈子,能否转正取决于ld的态度,只要他不卡,答辩就是走流程,个人觉得可以冲一把
投递字节跳动等公司9个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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