题解 | 合法IP C++最新做法

合法IP

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

#include <cctype>
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

bool isValidIP(vector<string>& vs) {
    if (vs.size() != 4) return false;
    for (auto& str : vs) {
        // cout << str << " " << endl;
        if(str.length() > 1 && str[0] == '0') return false;
        int sum = 0;
        for (int i = 0; i < str.length(); i++) {
            if (isdigit(str[i])) sum = sum * 10 + str[i] - '0';
            else return false;
        }
        if (sum < 0 || sum > 255) return false;
    }
    return true;
}

int main() {
    string sInput;

    while (getline(cin, sInput)) {
        int index = 0;
        vector<string> vs;
        while(sInput[index] == '.') index++;
        while (index < sInput.length()) {
            auto pos = sInput.find('.', index);
            // cout << pos << endl;
            string temp = sInput.substr(index, pos - index);
            index = pos + 1;
            if (temp.empty()) continue;
            vs.push_back(temp);
            if (pos == string::npos) break;
            
        }

        bool res = isValidIP(vs);

        cout << (res ? "YES" : "NO") << endl;
    }

    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

07-14 13:47
门头沟学院 Java
Lynn012:你评估好自己的位置了吗《顶尖应届》
投递小米集团等公司7个岗位
点赞 评论 收藏
分享
06-12 17:46
门头沟学院 Java
运营你豪哥:来说重点: ​1.项目前置,时间倒序。​​ 2.​项目描述强化结果与量化效果(STAR原则里的R)。​​ ​3.个人技能精炼,明确掌握程度,突出核心。​​ ​4.增加强有力开头的个人总结部分。​​ 5.​优化教育背景(成绩排名)、合并奖项与活动。​​
听劝,我这个简历该怎么改...
点赞 评论 收藏
分享
写不来代码的小黑:这么小的城市能有做it的公司也不容易
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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