华为机试题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; }