C++ 3ms straight-forward solution


  • 0
    M
        vector<string> ipToCIDR(string ip, int n) {
            unsigned int IP=0;
            string temp;
            for(int i=0;i<=ip.size();i++) {
                if(ip[i]=='.'||i==ip.size()) {
                    IP|=stoi(temp); 
                    if(i!=ip.size()) IP<<=8;
                    temp.clear();
                }
                else temp.append(1, ip[i]);
            } 
            IP+=n;   
            vector<string> res;
            while(n>0) {
                unsigned int temp=IP&(IP-1);
                int dif=IP-temp;
                while(dif>n) dif/=2;
                IP-=dif;
                n-=dif; 
                res.push_back(convert(IP, dif));
            }
            reverse(res.begin(), res.end());
            return res;
        }
        
        string convert(unsigned int a, int dif) {
            string res="";
            for(int i=0;i<4;i++) {
                int temp=a&255; 
                res=to_string(temp)+"."+res;
                a>>=8;
            }
            res.back()='/';  
            int len=1;
            while(dif!=1) {
                dif>>=1;
                len++;
            }
            return res+to_string(32-len+1);
        }

Log in to reply
 

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