题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
#include <cctype> #include <iostream> #include <string> using namespace std; bool isLegal(string IP){ string val=""; int cnt =0,cnt1=0; for(auto ch:IP){ if(!(isdigit(ch) || ch=='.')){ return false; } if(isdigit(ch)){ val+=ch; }else{//为.的情况 cnt++; if(val.size()>0){ int num = atoi(val.c_str()); if(! (num<256)){ return false; } if(num!=0){ int check_len=0; while(num/10>0 || num%10>0){ check_len++; num/=10; } if(check_len!=val.size()){ return false; } } cnt1++; val.clear(); } } } if(val.size()>0){ int num = atoi(val.c_str()); if(! (num<256)){ return false; } if(num!=0){ int check_len=0; while(num%10>0 || num/10 > 0){ check_len++; num/=10; } if(check_len!=val.size()){ return false; } } cnt1++; val.clear(); } //std::cout << cnt << "----" << cnt1 << std::endl; if(cnt!=3 || cnt1!=4){ return false; } return true; } int main(){ string IP; while(std::cin >> IP){ if(isLegal(IP)){ std::cout << "YES" << std::endl; }else{ std::cout << "NO" <<std::endl; } } return 0; }