题解 | #合法IP#
合法IP
http://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
利用sscanf取数,进行数字范围是否正确判断,与数字个数是否正确判断。
#include <stdio.h>
#include <string.h>
int f2(char *IP){
int n=strlen(IP);
int num[4]={-1};
sscanf(IP,"%d.%d.%d.%d",&num[0],&num[1],&num[2],&num[3]);
int count[4]={0};
char recode[4][3]={0};
for(int i=0;i<4;i++){
if(num[i]>=0&&num[i]<=255){
int temp=num[i];
if(temp==0){
count[i]=1;
recode[i][0]='0';
}else{
while(temp>0){
//recode[i][count[i]]=temp%10+'0';
count[i]++;
temp=temp/10;
}
}
}else{return 0;}
}
int sum=0;
for(int i=0;i<4;i++){
//if(memcmp(&IP[sum],recode[i],count[i]*sizeof(char))!=0){return recode[i+1][0]-'0'+10;}
sum+=count[i]+1;
}
if(sum-1!=n){return 0;}
return 1;
}
int main(){
char str[20]={0};
while(~scanf("%s",str)){
//printf("%d ",f2(str));
if(f2(str)){
printf("YES\n");
}else{printf("NO\n");}
}
}