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

查看4道真题和解析