852. IP轉化成CIDR

https://www.lintcode.com/problem/ip-to-cidr/description

這個題有點厲害,看了一下題解才明白啥意思:https://www.cnblogs.com/grandyang/p/8440087.html

class Solution {
public:
    long long split(string &ip) {
        long long x;
        int i=0;
        int j=0;
        while (i<ip.length()) {
            string tmp="";
            while (j<ip.length() && ip[j]!='.') {
                tmp=tmp+ip[j];
                j++;
            }
            x=x*256+(stoi(tmp));
            j++;
            i=j;
        }
        return x;
    }
    string convert(long long x, long long step) {
        string tmp=to_string((x>>24) & 255)+"."+to_string((x>>16) & 255)+"."+to_string((x>>8) & 255) +"."+to_string(x & 255);//直接位移並和11111111做&就可以
        //數字轉字符串用to_string, 字符串轉數字用stoi
        tmp=tmp+"/"+to_string(32-(int)(log2(step)));//加上最後取的位數,用log2(step)
        return tmp;
    }
    vector<string> ipToCIDR(string &ip, int n) {
        // Write your code here
        vector<string> res;
        long long x=split(ip); //把ip地址轉成10位整數
        while (n>0) {
            long long step= x & -x; //取從低到高第一個1的位置,倒數第x位返回pow(2,x)
            //也可以理解爲step代表的ip地址可以包含幾臺機器
            while (step>n) step=step/2;//如果機器數超過n(題目要求正好),就後移一位
            res.push_back(convert(x,step));//轉回ip地址的表示形式*
            x=x+step;//能表示機器的位數加一位,如果111(7)則+1=1000(8),1000(8)+8=10000(16)
            n=n-step;
        }
        return res;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章