题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
#include <stdio.h> #include <string.h> typedef struct{ unsigned char a1; unsigned char a2; unsigned char a3; unsigned char a4; }ipBYTE; typedef union{ unsigned int ipNum; ipBYTE ipByte; }IP_TYPE; int checkIP(int* aIp) { if((aIp[0] >= 0 && aIp[0] <= 255) && (aIp[1] >= 0 && aIp[1] <= 255) && (aIp[2] >= 0 && aIp[2] <= 255) && (aIp[3] >= 0 && aIp[3] <= 255)) return 1; else return 0; } int checkHideIp(int* aIp) { int flag0 = 0; for(int i = 3; i >= 0; i--) { if(aIp[i] != 0 && 0 == flag0) { flag0 = 1; continue; } if(aIp[i] != 0 && aIp[i] != 255) return 0; if(flag0 == 1 && aIp[i] == 0) return 0; } return 1; } int main() { int a1=0,a2=0,a3=0,a4=0; int aIp[4] = {-1}; int aIp1[4] = {-1}; int aIp2[4] = {-1}; IP_TYPE ip,ip1,ip2; while(EOF!=scanf("%d.%d.%d.%d",&aIp[0],&aIp[1],&aIp[2],&aIp[3])) { memset(aIp1, -1, sizeof(int)*4); scanf("%d.%d.%d.%d",&aIp1[0],&aIp1[1],&aIp1[2],&aIp1[3]); memset(aIp2, -1, sizeof(int)*4); scanf("%d.%d.%d.%d",&aIp2[0],&aIp2[1],&aIp2[2],&aIp2[3]); if(1 == checkIP(aIp) && 1== checkIP(aIp1) && 1 == checkIP(aIp2) && 1 == checkHideIp(aIp)) { ip.ipByte.a1 = aIp[3]; ip.ipByte.a2 = aIp[2]; ip.ipByte.a3 = aIp[1]; ip.ipByte.a4 = aIp[0]; ip1.ipByte.a1 = aIp1[3]; ip1.ipByte.a2 = aIp1[2]; ip1.ipByte.a3 = aIp1[1]; ip1.ipByte.a4 = aIp1[0]; ip2.ipByte.a1 = aIp2[3]; ip2.ipByte.a2 = aIp2[2]; ip2.ipByte.a3 = aIp2[1]; ip2.ipByte.a4 = aIp2[0]; if((ip.ipNum & ip1.ipNum) == (ip.ipNum & ip2.ipNum)) { printf("0\n"); }else { printf("2\n"); } }else printf("1\n"); } return 0; }