题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
#include <algorithm> #include<iostream> #include<string> #include<sstream> #include<vector> #include <bitset> using namespace std; bool judge_ip(string ip){ int j = 0; istringstream iss(ip); string seg; while(getline(iss,seg,'.')) if(++j > 4 || seg.empty() || stoi(seg) > 255) return false; return true; } bool is_private(string ip){ istringstream iss(ip); string seg; vector<int> v; while(getline(iss,seg,'.')) v.push_back(stoi(seg)); if(v[0] == 10) return true; if(v[0] == 172 && (v[1] >= 16 && v[1] <= 31)) return true; if(v[0] == 192 && v[1] == 168) return true; return false; } bool is_mask(std::string ip){ std::istringstream iss(ip); std::string seg; std::bitset<32> binaryMask; int octetIndex = 0; while(octetIndex < 4){ std::string octet; std::getline(iss,octet,'.'); int num = std::stoi(octet); if(num < 0 || num > 255 || octet.empty()) return false; binaryMask <<= 8; binaryMask |= num; octetIndex++; } std::string binaryStr = binaryMask.to_string(); size_t firstZero = binaryStr.find('0'); if(firstZero == std::string::npos) return false; //255.255.255.255 return std::all_of(binaryStr.begin()+firstZero,binaryStr.end(), [](char c){return c == '0';}); } int main(){ string input; int a = 0,b = 0,c = 0,d = 0,e = 0,err = 0,p = 0; while(cin >> input){ istringstream is(input); string add; vector<string> v; while(getline(is,add,'~')) v.push_back(add); if(!is_mask(v[1])){ int first = stoi(v[0].substr(0,v[0].find_first_of('.'))); if(istringstream(v[0]) && first != 0 && first != 127) err++; } else{ if(!judge_ip(v[0])) err++; else{ int first = stoi(v[0].substr(0,v[0].find_first_of('.'))); if(is_private(v[0])) p++; if(first > 0 && first <127) a++; else if(first > 127 && first <192) b++; else if(first > 191 && first <224) c++; else if(first > 223 && first <240) d++; else if(first > 239 && first <256) e++; } } } cout << a << " " << b << " " << c << " " << d << " " << e << " " << err << " " << p << endl; return 0; }