题解 | #合法IP#面向用例编程#较繁琐#纯C
合法IP
https://www.nowcoder.com/practice/995b8a548827494699dc38c3e2a54ee9
#include <stdio.h> #include <string.h> int main() { char str[20] = {'\0'}; scanf("%s", str); // 读入IP字符串 int symbol[4] = {0}; // 此数组用于标记'.'出现的位置 int symbolNum = 0; for (int i = 0; i < 20; i++) { if (str[i] == '.') { symbol[symbolNum] = i; symbolNum++; } } for (int i = 0; i < strlen(str); i++) { // 检查str中是否存在非数字和'.'字符的其他字符,如果有,非法,输出NO,结束 if (str[i] != '.' && (str[i] < '0' || str[i] > '9')) { printf("NO"); return 0; } } char str1[5] = {'\0'}; // 使用四个char数组来存储str中的四个数,后面借此判断各个数是否以0开头,如果是,非法 char str2[5] = {'\0'}; char str3[5] = {'\0'}; char str4[5] = {'\0'}; int a = 0, b = 0, c = 0, d = 0; for (int i = 0; i < symbol[0]; i++) { str1[a] = str[i]; a++; } for (int i = symbol[0] + 1; i < symbol[1]; i++) { str2[b] = str[i]; b++; } for (int i = symbol[1] + 1; i < symbol[2]; i++) { str3[c] = str[i]; c++; } for (int i = symbol[2] + 1; i < strlen(str); i++) { str4[d] = str[i]; d++; } if (strlen(str1) == 0 || strlen(str2) == 0 || strlen(str3) == 0 || strlen(str4) == 0) { // 用例中存在.开头以及..在中间的情况,此处处理 printf("NO"); return 0; } int num1 = 0, num2 = 0, num3 = 0, num4 = 0; // 将str中的四个char类型的字符串转化为int数字,用于判断IP是否非法 int factor1 = 1, factor2 = 1, factor3 = 1, factor4 = 1; for (int i = strlen(str1) - 1; i >= 0; i--) { num1 += (str1[i] - '0') * factor1; factor1 *= 10; } for (int i = strlen(str2) - 1; i >= 0; i--) { num2 += (str2[i] - '0') * factor2; factor2 *= 10; } for (int i = strlen(str3) - 1; i >= 0; i--) { num3 += (str3[i] - '0') * factor3; factor3 *= 10; } for (int i = strlen(str4) - 1; i >= 0; i--) { num4 += (str4[i] - '0') * factor4; factor4 *= 10; } if ((str1[0] == '0' && str1[1] != '\0') || (str2[0] == '0' && // 若某个str以0开头,则非法 str2[1] != '\0') || (str3[0] == '0' && str3[1] != '\0') || (str4[0] == '0' && str4[1] != '\0') || strlen(str4) == 0) { printf("NO"); } else if (num1 > 255 || num2 > 255 || num3 > 255 || num4 > 255) { // 若某个num大于255,则非法 printf("NO"); } else { printf("YES"); } return 0; }