题解 | #合法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; }