题解 | #合法IP#

合法IP

https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9

#include <cctype>
#include <iostream>
#include <bits/stdc++.h>
using namespace std;

bool check_(string s){
    for (auto ch : s){
        if (!isdigit(ch))
            return false;
    }
    int num_index = 0;
    if (s.size() > 1){
        for (auto ch : s){
            if (ch == '0' && num_index == 0)
                return false;
            if (ch != '0')
                num_index = 1;
        }
    }
    int x = stoi(s);
    if (x < 0 || x > 255)
        return false;
    return true;
}
int main() {
    string str;
    while (cin>>str){
        vector<string> vec;
        string tmp;
        for (int i = 0; i < str.size(); i++){
            if (i == str.size() - 1 ){
                tmp += str[i];
                vec.push_back(tmp);
            }
            if (str[i] == '.' && !tmp.empty()){
                vec.push_back(tmp);
                tmp = "";
            }
            else {
                tmp += str[i];
            }
        }
        int index = 0;
        if (vec.size() != 4){
            index = 1;
        }         
        for (auto it : vec){
            if (!check_(it)){
                index = 1;
            }
        }
        if (index)
            cout<<"NO";
        else
            cout<<"YES";
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

04-25 19:29
已编辑
宁波大学 运营
被普调的六边形战士很高大:你我美牛孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务