题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
精简版:
#include<stdio.h>
int validip(int* arr) {
for (int i = 0; i < 4; i++) {
if (arr[i] > 255 || arr[i] < 0)
return 0;
}
return 1;
}
int validmask(int* arr) {
unsigned mask;
int i;
if (!validip(arr))return 0;
for (i = 0, mask = 0; i < 4; i++) {
mask = mask * 256 + arr[i];
}
mask = ~mask;
while (mask & 1) {
mask >>= 1;
}
return mask?0:1;
}
unsigned tou(int* arr) {
unsigned u = 0;
for (int i = 0; i < 4; i++)
u = u * 256 + arr[i];
return u;
}
int main() {
int mask[4] = { -1,-1,-1,-1 }, ip1[4] = { -1,-1,-1,-1 }, ip2[4] = { -1,-1,-1,-1 };
char str[20];
while (scanf("%d.%d.%d.%d", mask,mask+1,mask+2,mask+3) != EOF) {
scanf("%d.%d.%d.%d", ip1, ip1 + 1, ip1 + 2, ip1 + 3);
scanf("%d.%d.%d.%d", ip2, ip2 + 1, ip2 + 2, ip2 + 3);
if (!(validmask(mask) && validip(ip1) && validip(ip2)))
printf("1\n");
else if ((tou(mask) & tou(ip1)) == (tou(mask) & tou(ip2)))
printf("0\n");
else
printf("2\n");
}
}
鲁棒版(可以接受地址某段没有数字的数据)
#include<stdio.h>
void to255(char* str, int* arr) {
int i = 0, j = 0, time = 0, seg = 0;
while (time < 4) {
j = i;
while (!(str[i] == '.' || str[i] == 0)) {
i++;
};
time++;
seg = 0;
while (j < i) {
seg = seg * 10 + str[j] - '0';
j++;
}
arr[time - 1] = seg;
if (time == 4)break;
i++;
if (str[i] == '.' || str[i] == 0) {//fatal error
for (int k = 0; k < 4; k++) {
arr[k] = -1;
}
return;
}
}
}
int validip(int* arr) {
for (int i = 0; i < 4; i++) {
if (arr[i] > 255 || arr[i] < 0)
return 0;
}
return 1;
}
int validmask(int* arr) {
unsigned mask;
int i;
if (arr[0] == -1 || !validip(arr))return 0;
for (i = 0, mask = 0; i < 4; i++) {
mask = mask * 256 + arr[i];
}
mask = ~mask;
while (mask & 1) {
mask >>= 1;
}
if (mask)
return 0;
else
return 1;
}
unsigned tou(int* arr) {
unsigned u = 0;
for (int i = 0; i < 4; i++) {
u = u * 256 + arr[i];
}
return u;
}
int main() {
int mask[4] = { 0,0,0,0 }, ip1[4] = { 0,0,0,0 }, ip2[4] = { 0,0,0,0 };
char str[20];
while (scanf("%s", str) != EOF) {
to255(str, mask);
scanf("%s", str);
to255(str, ip1);
scanf("%s", str);
to255(str, ip2);
if (!(validmask(mask) && validip(ip1) && validip(ip2))) {
printf("1\n");
}
else {
if ((tou(mask) & tou(ip1)) == (tou(mask) & tou(ip2)))
printf("0\n");
else
printf("2\n");
}
}
}