题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <algorithm>
#include <cctype>
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
//利用大数除法做进制转换;
string mTransTon(int m, string s, int n) {
int remain, len = s.size();
string res = "";
for (int i = 0; i < len; ) {
remain = 0;
for (int j = i; j < len; j ++) {
int temp = (remain * m + s[j] - '0') % n;
s[j] = (remain * m + s[j] - '0') / n + '0';
remain = temp;
}
res += char(remain + '0');
while (s[i] == '0') i++;
}
reverse(res.begin(), res.end());
return res;
}
string binTransToDec(string bin) {
bin += '.';
string subStr;
vector<string> f;
for (char c : bin) {
if (isdigit(c)) {
subStr += c;
} else if (c == '.') {
f.push_back(subStr);
subStr.clear();
}
}
string res;
for (auto it = f.begin(); it != f.end(); it ++) {
string sub = *it;
sub = mTransTon(10, *it, 2);
while (sub.size() < 8) sub = '0' + sub;
res += sub;
}
res = mTransTon(2, res, 10);
return res;
}
string decTransToBin(string dec) {
string binIP = mTransTon(10, dec, 2);
while (binIP.size() < 32) binIP = '0' + binIP;
vector<string> vec;
string subStr;
for (int i = 1; i <= binIP.size(); i++) {
if(i % 8 != 0) {
subStr += binIP[i-1];
}
else if(i % 8 == 0 && subStr.size()){
subStr += binIP[i-1];
vec.push_back(subStr);
subStr = "";
}
}
string res;
string subIP;
for (auto it = vec.begin(); it != vec.end(); it ++) {
subIP = mTransTon(2, *it, 10);
res += subIP;
res += '.';
}
res.erase(res.end() - 1);
return res;
}
int main() {
string bin, dec;
cin >> bin;
cin >> dec;
string transedBin = binTransToDec(bin);
cout << transedBin << endl;
string transedDec = decTransToBin(dec);
cout << transedDec << endl;
return 0;
}
// 64 位输出请用 printf("%lld")

