题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
#include <stdio.h> int ipvaild(int ip[]) { for(int i = 0;i<4;i++) { if(ip[i]<0 || ip[i]>255) { return 0; } } return 1; } void otob(int ziwa,int a[]) { int index = 7; while(ziwa!=0) { a[index--] = ziwa%2; ziwa/=2; } } int ziwavaild(int ziwa[]) { int a[4][8] = {0}; int flagz = 0; for(int i = 0;i<4;i++) { if(ziwa[i]<0 || ziwa[i]>255) { return 0; } otob(ziwa[i], a[i]); } for(int i = 0;i<4;i++) { for(int j = 0;j<8;j++) { if(a[i][j] == 0) { flagz = 1; } if(flagz) { if(a[i][j]==1) { return 0; } } } } return 1; } int main() { int ziwa[4] = {0}; int ip1[4] = {0},ip2[4] = {0}; /*int a = 128; int l[8] = {0}; otob(a, l); for(int i = 0;i<8;i++) { printf("%d",l[i]); }*/ while (~scanf("%d.%d.%d.%d",&ziwa[0],&ziwa[1],&ziwa[2],&ziwa[3])) { scanf("%d.%d.%d.%d",&ip1[0],&ip1[1],&ip1[2],&ip1[3]); scanf("%d.%d.%d.%d",&ip2[0],&ip2[1],&ip2[2],&ip2[3]); //int res[8] = {0}; if(ipvaild(ip1) && ipvaild(ip2) && ziwavaild(ziwa)) { int flag = 1; for(int i = 0;i<4;i++) { if((ip1[i]&ziwa[i]) != (ip2[i]&ziwa[i])) { flag = 0; break; } } if(flag) { printf("0\n"); }else { printf("2\n"); } }else { printf("1\n"); } } return 0; }