题解 | #合法IP#
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
#include <stdio.h> #include <string.h> int IPv4_verify(char *ip); int main() { char str[18]={0}; scanf("%s", str); int flag = IPv4_verify(str); if(flag) printf("YES\n"); else printf("NO\n"); return 0; } int IPv4_verify(char *ip) { int c[4] = {-1}; int count[4] = {0}; int n = strlen(ip); if(4 == sscanf(ip,"%d.%d.%d.%d", c, c+1, c+2, c+3) ) { for(int i = 0; i<4; i++) { if(c[i]<=255 && c[i] >=0) { int temp = c[i]; if(temp == 0) { count[i] = 1; } else { while(temp > 0){ //求数字长度 count[i]++; temp = temp/10; } } } else { return 0; } } int sum = 0; //注意对01.3.8.4为No,通过判断位数与长度是否相等来确定 for(int i = 0; i<4; i++) { sum += count[i] + 1; } if( sum - 1 != n ) { return 0; } return 1; } else return 0; }