题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
http://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
void toBinary(int, int[], int, int);
int two(int);
int sti(string);
int ip(string, int[], int);
void add(int[], int[], int);
int compare(int[], int[], int);
int compare(int a[], int b[], int n)
{
for (int i = 0; i < n; ++i)
{
if (a[i] != b[i])
return 2;
}
return 0;
}
int main()
{
int a[32] = {0};
int b[32] = {0};
int c[32] = {0};
int d[32] = {0};
int e[32] = {0};
int f[32] = {0};
int *shu[6] = {c, a, b, f, d, e};
string str;
int shuzu = 0;
int flag[6] = {1, 1, 1, 1, 1, 1};
while (getline(cin, str))
{
flag[shuzu] = ip(str, shu[shuzu], 32);
for (int m = 1; m < 32; ++m)
{
if ((shu[shuzu][m] - shu[shuzu][m - 1]) == 1)
flag[shuzu] = 0;
}
shuzu++;
int kk = 2;
while (kk)
{
getline(cin, str);
flag[shuzu] = ip(str, shu[shuzu], 32);
shuzu++;
--kk;
}
}
add(a, c, 32);
add(b, c, 32);
if ((flag[0] && flag[1] && flag[2]) == 0)
cout << 1;
else
cout << compare(a, b, 32);
cout << endl;
add(d, f, 32);
add(e, f, 32);
if ((flag[3] && flag[4] && flag[5]) == 0)
cout << 1;
else
cout << compare(d, e, 32);
return 0;
}
int ip(string str, int temp[], int n)
{
string str1 = "";
int j = 0;
int num = 0;
int location = 0;
for (int i = 0; i < str.size(); i++)
{
if (str[i] == '.')
{
j++;
if (str1 == "")
return 0;
num = sti(str1);
if (num > 255)
return 0;
toBinary(num, temp, n, location);
location += 8;
str1 = "";
}
else
str1 += str[i];
}
if (j != 3)
return 0;
num = sti(str1);
if (num > 255)
return 0;
toBinary(num, temp, n, location);
return 1;
}
void toBinary(int num, int temp[], int n, int beg)
{
for (int i = 0; i < 8; ++i)
{
if (num / two(7 - i) == 1)
{
temp[beg + i] = 1;
num -= two(7 - i);
}
else
temp[beg + i] = 0;
}
}
int two(int a)
{
if (a < 1)
return 1;
int result = 1;
while (a)
{
result *= 2;
a--;
}
return result;
}
int sti(string s)
{
size_t n = s.size() - 1;
int total = 0;
for (int i = 0; i <= n; ++i)
{
if (s[i] < '0' || s[i] > '9')
return 256;
int a = int(s[i] - '0');
int l = n - i;
int b = ceil(pow(10, l));
int temp = a * b;
total += temp;
}
return total;
}
void add(int a[], int b[], int n)
{
for (int i = 0; i < n; ++i)
{
a[i] = a[i] && b[i];
}
}
查看17道真题和解析