Accepted C++ Solution (6ms)


  • 0
    S
    template<typename Out>
         void split(const std::string &s, char delim, Out result) {
             std::stringstream ss;
             ss.str(s);
             std::string item;
             while (std::getline(ss, item, delim)) {
                 *(result++) = item;
             }
         }
    
    
         std::vector<std::string> split(const std::string &s, char delim) {
             std::vector<std::string> elems;
             split(s, delim, std::back_inserter(elems));
             return elems;
         }
    class Solution {
    public:
        vector<string> ipToCIDR(string ip, int range) {
            vector<string> retVec;
            auto vec = split(ip,'.');
            int value = stoi(vec[3]);
            int i = 1;
            while(i<4) {
                value+= stoi(vec[3-i])<<(8*i);
                ++i;
            }
            int count = 0;
            
            bitset<32> b(value);
            while(count<range) {
                int j = 0;
                for(;j<32;++j) {
                    if(b[j]==1) break;
                }
                auto c = 32-j;
                
                auto nC = pow(2,j);
                if(count+nC>range) {
                    auto needed = range-count;
                    while(needed<pow(2,j)) {
                        j--;
                    }
                    c = 32-j;
                    nC = pow(2,j);
                    count+=nC;
                    
                }
                else count+= nC;
                retVec.push_back(to_ip(b,c));
                for(;j<32;++j) {
                    if(b[j]==0) break;
                }
                b[j] = 1;
                while(j>0) {
                    j--;
                    b[j] = 0;
                }
                
            }
            return retVec;
        }
        string to_ip( bitset<32>& b,int c) {
            string retS;
            for(int i = 0;i<32;i=i+8) {
                int v = b[i];
                for(int j = 1;j<8;++j) {
                    int n = b[i+j];
                    v+= pow(2,j)*n;
                }
                if(i<24)retS = '.'+ to_string(v)+retS;
                else retS = to_string(v)+retS;
            }
            retS = retS+'/'+to_string(c);
            return retS;
        }
    };
    

  • 0
    S
    This post is deleted!

Log in to reply
 

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