题解 | #合法IP#

合法IP

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

#include <iostream>
#include <string>
#include <cctype>
#include <sstream>
using namespace std;
bool isValidIPAddress(const string &ip)
{
    istringstream iss(ip);
    string segment;
    unsigned count = 0;
    while (getline(iss, segment, '.'))
    {
        if (segment.empty() || segment.size() > 3)
        {
            return false;
        }
        if (segment[0] == '0' && stoi(segment) != 0)
        {
            return false;
        }
        for (char ch : segment)
        {
            if (!isdigit(ch))
            {
                return false;
            }
        }

        int num = stoi(segment);
        if (num < 0 || num > 255)
        {
            return false;
        }

        ++count;
    } 
    return count == 4;
}

int main() {
    string ip;
    cin >> ip;
    if (isValidIPAddress(ip))
        cout << "YES";
    else
        cout << "NO";
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

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