题解 | #合法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")

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 18:35
简历上把1个月实习写成了3个月,会进行背调吗?
码农索隆:一个月有一个月的实习经历,三个月有三个月的实习经历
点赞 评论 收藏
分享
07-01 17:14
中北大学 Java
兄弟们是真是假
牛客46374834...:我在boss上投java岗从来没成功过
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务