题解 | #识别有效的IP地址和掩码并进行分类统计#

识别有效的IP地址和掩码并进行分类统计

https://www.nowcoder.com/practice/de538edd6f7e4bc3a5689723a7435682

try
    flag = zeros(1, 7);
    while 1
        line = input('', 's');
        lines = strsplit(line, '~');
        yms = strsplit(cell2mat(lines(2)), '.');
        ipflag = 0;
        binyms = [];
        for i = 1:length(yms)
            bintemp = num2str(dec2bin(str2double(cell2mat(yms(i))), 8));
            binyms = strcat(binyms, bintemp);
        end
        if (~issorted(binyms, 'descend'))||(all(binyms=='1')||all(binyms=='0'))
            ipflag = 1;
        end
        ips = strsplit(cell2mat(lines(1)), '.');
        ipsn = zeros(1, 4);
        ipsn1 = str2double(cell2mat(ips(1)));
        ipsn(1) = ipsn1;
        if isempty(ipsn1)
            flag(6) = flag(6)+1;
            continue;
        end
        if length(ips)~=4
            flag(6) = flag(6)+1;
        elseif ipflag == 1&&~(ipsn1==0||ipsn1==127)
            flag(6) = flag(6)+1;
        elseif ipflag == 0
            for i = 2:4
                temp = str2double(cell2mat(ips(i)));
                if isempty(temp)
                    flag(6) = flag(6)+1;
                    continue
                end
                ipsn(i) = temp;
            end
            if max(ipsn)>255||min(ipsn)<0
                flag(6) = flag(6)+1;
            else
                if ipsn1>=1&&ipsn1<=126
                    flag(1) = flag(1)+1;
                elseif ipsn1>=128&&ipsn1<=191
                    flag(2) = flag(2)+1;
                elseif ipsn1>=192&&ipsn1<=223
                    flag(3) = flag(3)+1;
                elseif ipsn1>=224&&ipsn1<=239
                    flag(4) = flag(4)+1;
                elseif ipsn1>=240&&ipsn1<=255
                    flag(5) = flag(5)+1;
                end
                if ipsn1==10||(ipsn1==172&&ipsn(2)>=16&&ipsn(2)<=31)||(ipsn1==192&&ipsn(2)==168)
                    flag(7) = flag(7)+1;
                end
            end
        end
    end
catch
    fprintf('%d %d %d %d %d %d %d', flag(1), flag(2), flag(3), flag(4), flag(5), flag(6), flag(7));
end

全部评论

相关推荐

点赞 评论 收藏
分享
10-28 15:45
门头沟学院 C++
西南山:海康威视之前不是大规模裁员吗
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务