题解 | #识别有效的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;
}

全部评论

相关推荐

04-30 21:35
已编辑
长安大学 C++
晓沐咕咕咕:评论区没被女朋友好好对待过的计小将可真多。觉得可惜可以理解,毕竟一线大厂sp。但是骂楼主糊涂的大可不必,说什么会被社会毒打更是丢人。女朋友体制内生活有保障,读研女朋友还供着,都准备订婚了人家两情相悦,二线本地以后两口子日子美滋滋,哪轮到你一个一线城市房子都买不起的996清高计小将在这说人家傻😅
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务