题解 | #合法IP#

合法IP

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

#include<iostream>
#include<string>
#include<cstdlib>

using namespace std;

int main() {
    string s;
    while (cin >> s) {
        bool ip = true;
        int count = 0;
        for (int i = 0; i < s.size(); i++) {
            int num = 0;
            string temp = "";
            while (s[i] != '.' && i < s.size()) {
                temp = temp + s[i];
                i++;
            }
            count++;
            //判断是否出现0开头的数字(不是0),或者两个点连在一起的情况。
            if ((temp[0] == '0' && temp.size() > 1) || temp.size() == 0
                    || temp[0] == '+') {
                ip = false;
                break;
            }
            num = stoi(temp);
            if (num < 0 || num > 255) {
                ip = false;
                break;
            }
        }
        if (count != 4) ip = false; //判断是不是分隔为4个数字
        
        if (ip) cout << "YES" << endl;
        else cout << "NO" << endl;
    }
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务