题解 | #合法IP#

合法IP

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

#include <iostream>
using namespace std;
#include<sstream>
#include<vector>
bool isValid(string ip){
    stringstream ss(ip);
    string segment;
    vector<string> parts;
    while(getline(ss,segment,'.')){
        if(segment.empty()) return false; 
        parts.push_back(segment);
    }
    if(parts.size()!=4) return false; //4部分
    for(string part :parts){
        if(part=="0") return true; //单独一个0的情况是合法的
        if(part[0]=='0') return false; //前导零的情况
        if(stoi(part)<0||stoi(part)>255) return false; //范围
        for(char c:part){ //非数字情况
            if(!isdigit(c)) return false;
        }
    }
    return true;
}
int main() {
    string ip;
    while (getline(cin,ip)) {
        if(isValid(ip)){
            cout<<"YES"<<endl;
        }else{
            cout<<"NO"<<endl;
        }
    }
    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 14:10
啊啊啊啊好幸福,妈妈是我找工作发疯前的一束光
榕城小榕树:你是我见过最幸福的牛客男孩
点赞 评论 收藏
分享
06-26 17:24
已编辑
宁波大学 golang
迷失西雅图:别给,纯kpi,别问我为什么知道
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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