题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
unsigned int ip2Dec(string& str) {
vector<unsigned int> tokens;
string token;
istringstream iss(str);
while(getline(iss, token, '.')) {
tokens.push_back(stoi(token));
}
return (tokens[0] << 24) + (tokens[1] << 16) + (tokens[2] << 8) + tokens[3];
}
string Dec2Ip(unsigned int ip) {
string str = "";
str += to_string((ip & 0xFF000000) >> 24);
str += ".";
str += to_string((ip & 0x00FF0000) >> 16);
str += ".";
str += to_string((ip & 0x0000FF00) >> 8);
str += ".";
str += to_string((ip & 0x000000FF));
return str;
}
int main() {
string ip;
unsigned int ip10;
cin >> ip >> ip10;
cout << ip2Dec(ip) << endl;
cout << Dec2Ip(ip10);
}
// 64 位输出请用 printf("%lld")
注意使用unsigned int类型 int类型的右移算法取决于编译平台
#华为机试#华为OD机测试题 文章被收录于专栏
个人练习专栏
腾讯公司福利 1143人发布