题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
//https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682?tpId=37&tqId=21241&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title= #include <iostream> #include <string.h> #include <sstream> #include <vector> #include <bitset> #include <algorithm> using namespace std; int isip(string ip){ stringstream ss(ip); vector<string> num; while(getline(ss, ip, '.')) num.push_back(ip); if(num.size()!=4) return 0; for(auto c:num){ int ctem = stoi(c); if(0>ctem||ctem>255||c.size()==0) return 0; } return 1; } int ismask(string mask){ if(isip(mask)){ if(mask=="255.255.255.255"||mask=="0.0.0.0") return 0; stringstream ss(mask); string num; while(getline(ss, mask, '.')){ bitset<8> bit(stoi(mask)); num+=bit.to_string(); } int pos0 = num.find("0"); reverse(num.begin(), num.end()); int pos1 = num.find("1"); if((pos1+pos0)==32) return 1; else return 0; }else return 0; } int isprivate(string ip){ stringstream ss(ip); vector<string> num; while(getline(ss, ip, '.')) num.push_back(ip); if(num[0]=="10") return 1; if((num[0]=="172")&&(16<=stoi(num[1])&&(stoi(num[1])<=31))) return 1; if(num[0]=="192"&&num[1]=="168") return 1; return 0; } int main() { string s; int ans[7]; memset(ans, 0, sizeof(ans)); while (getline(cin, s)) { string ip, mask; stringstream ss(s); getline(ss, ip, '~'); getline(ss, mask, '~'); if(isip(ip)){ if(stoi(ip)==0||stoi(ip)==127) continue; if(ismask(mask)){ if(isprivate(ip)) ans[6]++; int ntem = stoi(ip); if(1<=ntem&&ntem<=126) ans[0]++; if(128<=ntem&&ntem<=191) ans[1]++; if(192<=ntem&&ntem<=223) ans[2]++; if(224<=ntem&&ntem<=239) ans[3]++; if(240<=ntem&&ntem<=255) ans[4]++; }else ans[5]++; }else{ ans[5]++; } } for(auto c:ans) cout << c << ' '; }