原题链接:https://vjudge.net/problem/UVA-1590
分类:函数
备注:二进制
题意解释:对于给出个m个IP地址,按照"byte0.byte1.byte2.byte3"从前往后数,连续的最长相同序列的长度就为题目要求的32-n,(注意:不论这个序列最后一位是不是0,我在这里被坑了一下),前32-n位不动,后n位则是可以任意变动的,将其都置0再输出就可以了,子网掩码则是前32-n位置1,后n位置0然后输出。
代码如下:
#include
const int maxm = 1000 + 5;
int m, binary[maxm][35];
void Put(int pos)
{
int a = 0, b = 0, c = 0, d = 0;
int A = 0, B = 0, C = 0, D = 0, ans[35] = { 0 };
for (int i = pos; i <= 32; i++)
binary[m][i] = 0;
for (int i = 1; i = 1; i--)
{
a += binary[m][i] << (8 - i);
A += ans[i] <= 9; i--)
{
b += binary[m][i] << (16 - i);
B += ans[i] <= 17; i--)
{
c += binary[m][i] << (24 - i);
C += ans[i] <= 25; i--)
{
d += binary[m][i] << (32 - i);
D += ans[i] << (32 - i);
}
printf("%d.%d.%d.%d\n%d.%d.%d.%d\n", a, b, c, d, A, B, C, D);
}
int main(void)
{
while (~scanf("%d", &m))
{
int a, b, c, d, pos = 33;
for (int i = 1; i = 1; j--) { binary[i][j] = a % 2; a /= 2; }
for (int j = 16; j >= 9; j--) { binary[i][j] = b % 2; b /= 2; }
for (int j = 24; j >= 17; j--) { binary[i][j] = c % 2; c /= 2; }
for (int j = 32; j >= 25; j--) { binary[i][j] = d % 2; d /= 2; }
}
for (int j = 1; j <= 32; j++)
{
int tmp = binary[1][j], flag = 0;
for (int i = 2; i <= m; i++)
if (tmp != binary[i][j]) { flag = 1; break; }
if (flag) { pos = j; break; }
}
Put(pos);
}
return 0;
}