华为机试题HJ33-题解 | #整数与IP地址间的转换#

整数与IP地址间的转换

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

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <stdlib.h>

using namespace std;

vector<string> Split(const string& strInput, char split = '.') {
    vector<string> splitVec;
    size_t len = strInput.size();
    size_t start = 0;
    size_t end = 0;
    string strTemp = "";
    size_t it = 0;
    while ((it = strInput.find(split, start)) != string::npos  && start < len) {
        end = it;
        strTemp = strInput.substr(start, end - start);
        splitVec.push_back(strTemp);
        start = end + 1;
    }
    splitVec.push_back(strInput.substr(start));
    return splitVec;
}

long ConvertIp(const string& strIp) {
    long ip = 0;
    vector<string> ipVec = Split(strIp, '.');
    for (int i = 0; i < ipVec.size(); i++) {
        long nTemp = atol(ipVec[i].c_str());
        ip += nTemp << ((ipVec.size() - i - 1) * 8); // 24 16 8
    }
    return ip;
}

string ConvertToIpString(long ip) {
    string strIp = "";
    long nTemp = ip >> 24;
    ip = ip - (nTemp << 24);
    strIp += std::to_string(nTemp);
    nTemp = ip >> 16;
    ip = ip - (nTemp << 16);
    strIp += ".";
    strIp += std::to_string(nTemp);
    nTemp = ip >> 8;
    ip = ip - (nTemp << 8);
    strIp += ".";
    strIp += std::to_string(nTemp);
    nTemp = ip;
    strIp += ".";
    strIp += std::to_string(nTemp);
    return strIp;
}

int main() {
    string strIp;
    long ip;
    while (cin >> strIp >> ip) { // 注意 while 处理多个 case
        cout << ConvertIp(strIp) << endl;
        cout << ConvertToIpString(ip) << endl;
    }

    return 0;
}

全部评论

相关推荐

10-09 09:39
门头沟学院 C++
HHHHaos:这也太虚了,工资就一半是真的
点赞 评论 收藏
分享
dongsheng66:如果想进大厂的话,在校经历没必要占这么大篇幅,可以把专业技能单独放一个专栏写,可以加个项目经历
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务