文章目录
零、原题链接
一、题目描述

二、测试用例

三、解题思路
- 基本思路:
利用 IP 地址和整数的转换规则,IP 地址 → \rightarrow → 整数,每个数字乘对应位权的累加和;整数 → \rightarrow → IP地址,不断除以位权; - 具体思路:
- IP 地址 → \rightarrow → 整数,分割 IP 地址,第 i 个数字的位权为 256 4 − i 256^{4-i} 2564−i
- 整数 → \rightarrow → IP 地址,除以对应位权,商作为第 i 个数字,余数用于求下一个数字。
四、参考代码
时间复杂度: O ( 1 ) \Omicron(1) O(1)
空间复杂度: O ( 1 ) \Omicron(1) O(1)
cpp
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
stringstream ss;
string str;
cin >> str;
ss << str;
long num = 0;
long t = 256 * 256 * 256;
while (getline(ss, str, '.')) {
num += stoi(str) * t;
t /= 256;
}
cout << num << endl;
cin >> num;
str = "";
t = 256 * 256 * 256;
for (int i = 0; i < 3; i++) {
str += to_string(num / t) + ".";
num %= t;
t /= 256;
}
str += to_string(num);
cout << str << endl;
}
// 64 位输出请用 printf("%lld")