题解 | 整数与IP地址间的转换
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <iostream>
#include <string>
using namespace std;
bool hasDot(string s){
for(const auto &c : s){
if(c == '.') return true;
}
return false;
}
/**
* 10禁止字符串转2进制字符串模拟
*/
string tenToTwo(string s, int bits){
int num = 0;
for(const auto &c : s){
num = num * 10 + c - '0';
}
string res;
for(int i = bits; i >= 0; i -- ){
res.push_back(((num >> i) & 1) + '0');
}
return res;
}
/**
* 二进制字符转10进制数
*/
unsigned int twoToTen(string s){
unsigned int num = 0;
for(const auto &c : s){
num = num * 2 + c - '0';
}
return num;
}
void ipToInt(string ip){
string s;
string ans;
for(const auto &c : ip){
if(c == '.'){
ans.append(tenToTwo(s, 7));
s.clear();
}else{
s.push_back(c);
}
}
ans.append(tenToTwo(s, 7));
cout << twoToTen(ans) << "\n";
}
// =======================
void intToIp(string s){
string ans = tenToTwo(s, 31);
string res;
string ip;
for(int i = 0; i < ans.size(); i ++ ){
if(i != 0 && i % 8 == 0){
string numStr = to_string(twoToTen(res));
ip.append(numStr);
ip.push_back('.');
res.clear();
}
res.push_back(ans[i]);
}
string numStr = to_string(twoToTen(res));
ip.append(numStr);
cout << ip << "\n";
}
int main() {
string ip;
while(cin >> ip){
if(hasDot(ip)){
ipToInt(ip);
}else{
intToIp(ip);
}
}
return 0;
}
// 64 位输出请用 printf("%lld")
这题真的很烦!
