题解 | #合法IP#
合法IP
http://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
应该把各种情况考虑全了,应该
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
bool isNum(string str){ // 判断单段字符串 IP
if(str.empty()) return 0; // 为空不合法
if(str =="0") return 1; // 单 0 合法
if(str[0]=='0') return 0; // 首位为0 的不合法
for(auto c : str){
if(!isdigit(c)) // 出现字母不合法
return 0;
}
int num = stoi(str); // 转为整型判断
if(num>255) return 0;
return 1;
}
int main(){
string ip;
while(getline(cin, ip)){
stringstream ss(ip);
string str1;
int sig = 1; // 截至目前均为合法
int i=0; // 统计输出次数
while(getline(ss,str1,'.')){// 以 . 分割字符串
if(!isNum(str1)){
sig = 0;
break;
}
i++; // 统计分割段数,鉴别 1.20.3 这种情况
}
if(i!=4) sig=0;
if(sig==1)
cout<<"YES";
else cout<<"NO";
cout<<endl;
}
return 0;
}