题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
不太好的方法......
比较麻烦
#include <iostream> #include <stdio.h> #include <string> #include <vector> using namespace std; int errno,num_A,num_B,num_C,num_D,num_E,num_PRI = 0; // 判断ip情况 void ip_type(vector<int> v){ int b = v[0]; int c = v[1]; if(b >= 1 && b <= 126){ num_A++; if(b == 10){ num_PRI++; } } else if(b >= 128 && b <= 191){ num_B++; if(b == 172 && ((c >= 16)&&(c <= 31))){ num_PRI++; } } else if(b >= 192 && b <= 223){ num_C++; if(b == 192 && c == 168 ){ num_PRI++; } } else if(b >= 224 && b <= 239){ num_D++; } else if(b >= 240 && b <= 255){ num_E++; } return; } // 判断mask情况 bool is_maskleg(vector<int> v){ int one = v[0]; int two = v[1]; int three = v[2]; int four = v[3]; //全0或全1 if(one == 0 && two == 0 && three == 0 && four == 0){ return false; } else if(one == 255 && two == 255 && three == 255 && four == 255){ return false; } int i = 0; while(v[i] == 255 && i <4){ i++; continue; } //符合要求 //不要忘了0的情况 if(v[i] == 128 || v[i] == 192 || v[i] == 224 || v[i] == 240 || v[i] == 248 || v[i] == 252 || v[i] == 254 || v[i] == 0 ){ for(int j=i+1; j < 4; j++){ if(v[j] != 0){ return false; } else{ continue; } } return true; } else{ return false; } return false; } // 统一判断是否合法 // v是传出参数,用引用作为参数 bool commen(string str,vector<int>& v){ int dot = 0; string s; for(int i = 0; i < str.length(); i++){ while(str[i] != '.' && i < str.length()){ s += str[i]; i++; } //不是最后一个,就加一个. if(i != str.length()){ dot++; } //如果有两个.连在一起 if(s.size() > 0){ v.push_back(stoi(s)); } //排除两个点连在一起或是最后一个是点的情况 else if(s.size() == 0 || str[str.length()-1] == '.'){ return false; } s.clear(); } //不是四个字节或.数不是3 if(dot != 3 || v.size() != 4){ return false; } //单个数不在0~255范围内 for(int i = 0; i < 4; i++){ int a = v[i]; //非法的ip if(a < 0 || a > 255){ return false; } } return true; } int main(){ string str; while(getline(cin,str)){ int i=0; string ip; while(str[i] != '~'){ ip += str[i]; i++; } i++; //没有substring,但有substr string mask = str.substr(i,str.length()-i); vector<int> v1; vector<int> v2; bool p = commen(ip,v1); bool q = commen(mask,v2); //如果ip和mask都符合格式 if(p & q){ //是0或127开头的,不用判断mask是否合法,直接忽略 if((v1[0] == 0) || (v1[0] == 127)){ continue; } //判断mask是否合法,合法就判断类型,否则errno加一 else{ if(is_maskleg(v2)){ ip_type(v1); } else{ errno++; continue; } } } //不都符合格式 else if(!(p & q)){ errno++; continue; } } cout << num_A << ' ' << num_B << ' ' << num_C << ' ' << num_D << ' ' << num_E << ' ' << errno << ' ' << num_PRI; return 0; }