题解 | #合法IP# 很多边界条件需要注意
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
#include <iostream> using namespace std; int main() { string ip; auto checkStr = [](string & str) { // 注意这个边界条件,子串必须不为空 if (str.size() == 0) { return false; } for (int i = 0; i < str.size(); i++) { char c = str[i]; // 首字符是0且string长度大于1也不是合法IP,只有字符长度是1的情况下才合法 if (i == 0 && str.size() > 1 && c == '0') { return false; } // 非数字不是合法IP if (!std::isdigit(c)) { return false; } } // 数字范围在0 ~255 int num = std::stoi(str); if (num < 0 || num > 255) { return false; } return true; }; while (getline(cin, ip)) { int parts = 0; auto pos = ip.find('.'); string res("YES"); while (pos != string::npos) { auto subStr = ip.substr(0, pos); if (!checkStr(subStr)) { res = "NO"; break; } parts++; ip = ip.substr(pos + 1); pos = ip.find('.'); } // check最后一part if (!checkStr(ip)) { res = "NO"; } parts++; // 必须有四部分且合格 if (parts != 4) { res = "NO"; } cout << res << endl; } } // 64 位输出请用 printf("%lld")