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

全部评论

相关推荐

jack_miller:我给我们导员说我不在这里转正,可能没三方签了。导员说没事学校催的时候帮我想办法应付一下
点赞 评论 收藏
分享
10-15 03:05
门头沟学院 Java
CADILLAC_:凯文:我的邮箱是死了吗?
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务