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

整数与IP地址间的转换

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

#include <iostream>
#include <vector>
#include <sstream>
using namespace std;



string decimalToBinary(long long nInput) {
    if (nInput == 0) return "00000000";

    string strBinary = "";
    while (nInput > 0) {
        strBinary = to_string(nInput & 1) + strBinary;
        nInput >>= 1; // 等同于 n = n / 2;
    }

    while (strBinary.size() < 8) {
        strBinary.insert(0, "0");
    }
    return strBinary;
}

long long binaryToDecimal(string strBinary) {
    long long nDecimal = 0;
    for (char chBit : strBinary) {
        nDecimal = (nDecimal << 1) + (chBit - '0');
    }
    return nDecimal;
}


vector<string> split(char chSigned, const string& strInput) {
    vector<string> vecTokens;
    string strToken;
    istringstream tokenStream(strInput);
    while (getline(tokenStream, strToken, chSigned)) {
        vecTokens.push_back(strToken);
    }
    return vecTokens;
}

int main() {
    string strInput;
    while (getline(cin, strInput)) {
        if (strInput.find(".") != -1) {
            vector<string> vecTokens = split('.', strInput);
            vector<string> vecBinary;
            for (string strVal : vecTokens) {
                vecBinary.push_back(decimalToBinary(stoll(strVal)));
            }

            string strTotalBinary = "";
            int nIndex = 0;
            long long nOutput = 0;
            for (string strVal : vecBinary) {
                nIndex++;
                strTotalBinary.append(strVal);

                if (nIndex == vecBinary.size()) {
                    nOutput = binaryToDecimal(strTotalBinary);
                }
            }

            cout << nOutput <<  endl;

        } else {
            string strTotalBinary2 = decimalToBinary(stoll(strInput));

            while (strTotalBinary2.size() < 32) {
                strTotalBinary2.insert(0, "0");
            }

            vector<string> vecBinary2;
            int nIndex2 = 0;
            while (++nIndex2 && (nIndex2 != 5)) {
                vecBinary2.push_back(strTotalBinary2.substr((nIndex2 - 1) * 8, 8));
            }

            string strAddress2 = "";
            int nIndex20 = 0;
            for (string strVal : vecBinary2) {
                nIndex20++;
                if (nIndex20 != vecBinary2.size()) {
                    strAddress2.append(to_string(binaryToDecimal(strVal)) + ".");
                } else {
                    strAddress2.append(to_string(binaryToDecimal(strVal)));
                }
            }
            cout << strAddress2 <<  endl;
        }
    }

}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

09-24 17:55
门头沟学院 Java
码农索隆:多好,多直白
我的秋招日记
点赞 评论 收藏
分享
今天 10:17
安徽大学 Java
点赞 评论 收藏
分享
09-24 18:30
已编辑
长春工业大学 产品经理
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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