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