题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
#include <cctype>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() {
string strs;
cin >> strs; //得到输入的数据
stringstream input(strs); //将数据变成流的形式
vector<int> NUM; //保存数据的容器
string data; //临时保存数据的地方
while(getline(input,data,'.'))
{
if (data == "\0")
{
break;
}
else if (data.size() > 1 && data[0] == '0')
{
break; // 数字有前导0
}
for (char c : data)
{
if (!isdigit(c))
{
data = "10000"; //如果输入的数据包含字符,则把data赋值一个不属于ip地址的数
break;
}
}
NUM.push_back(stoi(data));
}
if (NUM.size() != 4)
{
cout << "NO";
}
else
{
int cnt = 0;
for (auto it : NUM)
{
if (it <= 255 && it >= 0)
{
cnt += 1;
}
}
if (cnt == 4)
{
cout << "YES";
}
else
{
cout << "NO";
}
}
}
// 64 位输出请用 printf("%lld")

