题解 | #整数与IP地址间的转换# C++ 注意整数溢出
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <iostream> #include <bitset> #include <sstream> using namespace std; int64_t ip_to_int(string ip) { stringstream ss(ip); string s; int64_t res = 0; // 183.31.75.22 // 1675978389 int rate = 24; while (getline(ss, s, '.')) { res |= (stoll(s) << rate); rate -= 8; } return res; } string int_to_ip(long long num) { string res; for (int i = 0; i < 3; ++i) { res = "." + to_string(num % 256) + res; num >>= 8; } res = to_string(num) + res; return res; } int main() { string ip; long long num; while (cin >> ip >> num) { cout << ip_to_int(ip) << endl; cout << int_to_ip(num) << endl; } return 0; }