题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 验证IP地址 * @param IP string字符串 一个IP地址字符串 * @return string字符串 */ #include <string.h> int ipv4(char* IP) { char* p = IP; int num = 0; int d = 0; do { if (*p == '.' || *p == '\0') { if (num > 255) return -1; d++; num = 0; if (*p == '\0') break ; p++; } if (*p >= '0' && *p < '9') { if (num == 0 && *p == '0' && *(p + 1) != '.') { return -1; } num = (*p - '0') + num * 10; } else { return -1; } } while (*p++ != '\0'); if (d != 4) return -1; return 0; } int ipv6(char* IP) { char* p = IP; int num = 0; int d = 1; do { if (*p == ':' || *p == '\0') { if(num==0||num>4){ return -1; } d++; num=0; if(*p=='\0'){ break; } p++; } if ((*p >= '0' && *p <= '9' )||( *p >= 'a' && *p <= 'f' )|| (*p >= 'A' && *p <= 'F')) { p++; num++; } else { return -1; } } while (*p != '\0'); if (d != 8) { return -1; } return 0; } char* solve(char* IP ) { // write code here char* p = IP; int flag = 0; while (*p != '\0') { if (*p == '.') { flag = 1; break; } if (*p == ':') { flag = -1; break ; } p++; } if (flag == 1) { if (ipv4(IP) == 0) { return "IPv4"; } } if (flag == -1) { if (ipv6(IP) == 0) { return "IPv6"; } } return "Neither"; }