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

全部评论

相关推荐

04-28 19:31
门头沟学院 Java
真烦好烦真烦:可恶的二手车贩子,居然对我们门头沟学院的人这么没礼貌
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务