算法竞赛入门经典第四章习题4-5 IP Networks UVA - 1590

习题4-5
https://vjudge.net/problem/UVA-1590
这题其实不如自己写函数转换进制来的实在
bitset类

int a=99;
bitset<8> bint(a);//把a转化为8为二进制存放在bint中
cout<<bint.to_ulong()<<endl;//输出把bint转换为十进制后的数
#include<iostream>
#include<string>
#include<sstream>
#include<bitset>
#include<cstring>
#pragma warning(disable:4996)
using namespace std;
void P(string s) {
    bitset<8> bint;
    stringstream S(string(s, 0,8));
    S >> bint;
    cout << bint.to_ulong();
    S.str(string(s, 8, 8));
    S >> bint;
    cout <<"."<< bint.to_ulong();
    S.str(string(s, 16, 8));
    S >> bint;
    cout << "." << bint.to_ulong();
    S.str(string(s, 24, 8));
    S >> bint;
    cout << "." << bint.to_ulong() <<endl;
}
int main() {
#ifdef _DEBUG
    //freopen("in", "rb", stdin);
    //freopen("out", "wb", stdout);
#endif // _DEBUG

    int n;
    while (cin >> n) {
        string s;
        string sta[1002];
        int top = -1;
        while (n--) {
            cin >> s;
            for (int i = 0; i < s.size(); ++i)
                if (s[i] == '.') s[i] = ' ';
            int a[4];
            sscanf(s.c_str(), "%d %d %d %d", a, a + 1, a + 2, a + 3);
            s = "";
            for (int i = 0; i < 4; ++i) {
                bitset<8> bs(a[i]);
                stringstream S;
                S << bs;
                s += string(8 - S.str().size(), '0') + S.str();
            }
            sta[++top] = s;
        }
        int i = 0;
        bool _end = false;
        for (; i < 32; ++i) {
            for (int j = 1; j <= top; ++j)
                if (sta[j][i] != sta[0][i]) {
                    _end = true; break;
                }
            if (_end) break;
        }
        s = string(i, '1') + string(32 - i, '0');
        for (; i < 32; ++i)
            sta[0][i] = '0';
        P(sta[0]);
        P(s);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值