题解 | #合法IP#|这个写法比较好理解

合法IP

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

#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
bool isNotDigitStr(string s) {
    for (auto u : s) {
        if (!isdigit(u)) {
            return true;
        }
    }
    return false;
}
int main() {
    string ip;
    while (getline(cin, ip)) { // 注意 while 处理多个 case
        string a, b, c, d;
        //1.确保有3个.
        if (count(ip.begin(), ip.end(), '.') < 3) {
            cout << "NO" << endl;
        } else {
            //2.分割获取4个分段值,针对.1.3.8或1..3.6等,确保ip的4个分段值非空
            a = ip.substr(0, ip.find('.'));
            ip.erase(0, ip.find('.') + 1);
            b = ip.substr(0, ip.find('.'));
            ip.erase(0, ip.find('.') + 1);
            c = ip.substr(0, ip.find('.'));
            ip.erase(0, ip.find('.') + 1);
            d = ip;
            if (a == "" || b == "" || c == "" || d == "" || isNotDigitStr(a) ||//3.确保不含非数字字符
                    isNotDigitStr(b) || isNotDigitStr(c) || isNotDigitStr(d)) {
                cout << "NO" << endl;
            } else if ((a.size() >= 2 && stoi(a) < pow(10, a.size() - 1)) ||//4.确保不含前导0
                       (b.size() >= 2 && stoi(b) < pow(10, b.size() - 1)) ||
                       (c.size() >= 2 && stoi(c) < pow(10, c.size() - 1)) ||
                       (d.size() >= 2 && stoi(d) < pow(10, d.size() - 1))) {
                cout << "NO" << endl;
            } else if (!((stoi(a) >= 0 && stoi(a) <= 255) && (stoi(b) >= 0 &&//5.确保数字范围符合
                         stoi(b) <= 255) && (stoi(c) >= 0 && stoi(c) <= 255) && (stoi(d) >= 0 &&
                                 stoi(d) <= 255))) {
                cout << "NO" << endl;
            } else {
                cout << "YES" << endl;
            }
        }
    }
    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
02-12 18:14
RT,这周五就是情人节了,前女友给我发了消息,我该不该回?
Yoswell:原则上来说让她滚,但是本着工作很累下班想吃瓜的心态,我觉得你可以回一下
点赞 评论 收藏
分享
MingoTree:看不出你你的技术栈,想找什么工作,然后课设项目别写上去了,自我评价删了,前后端你想好你要干啥,这种简历投上去秒挂的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务