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;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值