accepted c++


  • 0
    F
    vector<string> ipToCIDR(string ip, int range) {
        auto str2ip = [] (const string& s) {
            unsigned ret = 0;
            for (auto it = s.begin(); it < s.end();) {
                auto next = find(it, s.end(), '.');
                ret = 256*ret + atoi(string{it, next}.c_str());
                it = next+1;
            }
            return ret;
        };
        auto ip2str = [](unsigned ip) {
            string ret = to_string(ip>>24) + '.' + to_string((ip>>16)&0xff)
            + '.' + to_string((ip>>8)&0xff) + '.' + to_string(ip & 0xff);
            return ret;
        };
    
        auto l = str2ip(ip);
        auto r = l + range-1;
        vector<string> ret;
        vector<string> additional;
        for (unsigned bit = 0; l <= r; ++bit) {
            auto bval = (1<<bit);
            if (bval & l) {
                ret.push_back(ip2str(l));
                ret.back() += '/';
                ret.back() += to_string(32-bit);
                l += bval;
            }
            if ((bval & r) == 0) {
                additional.push_back(ip2str(r & ~(bval-1)));
                additional.back() += '/';
                additional.back() += to_string(32-bit);
                r -= bval;
            }
        }
        ret.insert(ret.end(), additional.rbegin(), additional.rend());
        return ret;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.