题解 | #识别有效的IP地址和掩码并进行分类统计#
识别有效的IP地址和掩码并进行分类统计
https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682
#include <iostream>
#include <bits/stdc++.h>
#include <vector>
using namespace std;
vector<string> add_(string s){
vector<string> vec;
string tmp;
for (int i = 0; i < s.size(); i++) {
if (i == s.size() - 1 ) {
tmp += s[i];
vec.push_back(tmp);
}
if (s[i] == '.' && !tmp.empty()) {
vec.push_back(tmp);
tmp = "";
} else {
tmp += s[i];
}
}
return vec;
}
bool check_ip(vector<string> vec) {
//四个部分
if (vec.size() != 4) {
return false;
}
for (auto it : vec) {
//数字
for (auto ch : it) {
if (!isdigit(ch))
return false;
}
//0在数字前
int num_index = 0;
if (it.size() > 1) {
for (auto ch : it) {
if (ch == '0' && num_index == 0)
return false;
if (ch != '0')
num_index = 1;
}
}
if (stoi(it) < 0 || stoi(it) > 255)
return false;
}
return true;
}
bool check_mask(vector<string> vec){
if (!check_ip(vec))
return false;
string tmp;
for (auto it : vec){
int n = stoi(it);
bitset<8> foo(n);
tmp += foo.to_string();
}
int zero_index = 0;
int one_index = 0;
for (auto it : tmp){
if (it == '1')
one_index = 1;
if (it == '0')
zero_index = 1;
if (it == '1' && zero_index == 1)
return false;
}
//只有0/1
if ((one_index == 1 && zero_index == 0) || (one_index == 0 && zero_index == 1))
return false;
return true;
}
int main() {
string str;
int A = 0,B = 0,C = 0,D = 0,E = 0,erro = 0,self = 0;
while(cin>>str){
string ip, mask;
for (int i = 0; i < str.size(); i++){
if (str[i] == '~'){
ip = str.substr(0, i);
mask = str.substr(i + 1, str.size() - i - 1);
}
}
vector<string> v_ip = add_(ip);
vector<string> v_mask = add_(mask);
//特殊
if (v_ip[0] == "0"|| v_ip[0] == "127") continue;
//erro
if (!check_ip(v_ip) || !check_mask(v_mask)){
erro++;
continue;
}
//私网
if (v_ip[0] == "10"){
self++;
//continue;
}
if (v_ip[0] == "192" && v_ip[1] == "168"){
self++;
//continue;
}
if (v_ip[0] == "172" && (stoi(v_ip[1]) >= 16 && stoi(v_ip[1]) <= 31)){
self++;
//continue;
}
//abcde
int n = stoi(v_ip[0]);
if (n <= 126){
A++;
continue;
}
else if (n <= 191){
B++;
continue;
}
else if (n <= 223){
C++;
continue;
}
else if (n <= 239){
D++;
continue;
}
else{
E++;
continue;
}
}
cout<<A<<' '<<B<<' '<<C<<' '<<D<<' '<<E<<' '<<erro<<' '<<self;
}
// 64 位输出请用 printf("%lld")
