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

全部评论

相关推荐

看到这个内容真是闹麻了。。。。。。现在有了AI以后很多人面试都会作弊吗?&nbsp;那对老老实实面试的人岂不是不公平....
程序员牛肉:公平那是对小孩子讲的童话故事,成年人的世界只有能不能接受失败的后果。 你要是能接受面试作弊被发现之后多家公司联合永久拉黑的后果,你就搞。
点赞 评论 收藏
分享
下个早班:秒挂就是不缺人
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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