题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <iostream> #include <iterator> #include <string> #include <algorithm> #include <cmath> using namespace std; int main() { string s1,s2; cin >> s1; cin >> s2; s1 += '.'; int n1 = s1.size(), n2 = s2.size(); // 转换为10进制 string s; string res; for(int i = 0; i<n1; i++){ if(s1[i] != '.'){ s += s1[i]; } else { int num = stoi(s), j = 7; string ss = "00000000"; while(num){ int tm = num % 2; if(tm){ ss[j] = '1'; } j--; num /= 2; } res += ss; s.clear(); } } long res1=0, n3 = res.size(); for(int i=0;i<n3;i++){ res1 += (res[n3-1-i] - '0') * pow(2,i); } cout << res1 << endl; // 转换为ip地址 long num2 = stol(s2); string res2; while(num2){ int t1 = 0; int tmp=0; for(int i=0; i<8; i++){ tmp += (num2 % 2) * pow(2, t1++); num2 = num2 >> 1; } res2 = "." + to_string(tmp) + res2; } res2.erase(0, 1); cout << res2 << endl; return 0; } // 64 位输出请用 printf("%lld")
除了转换逻辑外还需要注意数据的范围,这道题要用long 而不是 int 作为结果输出