题解 | #整数与IP地址间的转换#
整数与IP地址间的转换
https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea
#include <iostream> #include <bitset> #include <string> #include <vector> using namespace std; int main() { string ip; getline(cin,ip); string longip; getline(cin,longip); vector<int> ippart(4,0); for(int i = 0;i!=3;++i) { ippart[i] = stoi(ip.substr(0,ip.find('.'))); ip = ip.substr(ip.find('.')+1,ip.size()); } ippart[3] = stoi(ip); string bi = ""; for(auto i:ippart) { bitset<8> b(i); bi+=b.to_string(); } bitset<32> k(bi); cout<<k.to_ullong()<<endl; k = bitset<32>(stoll(longip)); bi = k.to_string(); for(int i = 0;i!=4;++i) { bitset<8> b(bi.substr(i*8,8)); if(i!=3) cout<<b.to_ullong()<<"."; else cout<<b.to_ulong(); } return 0; } // 64 位输出请用 printf("%lld")
有一个trick,就是int的范围很小,所以要用stoll