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



查看10道真题和解析