题解 | #判断两个IP是否属于同一子网#
判断两个IP是否属于同一子网
https://www.nowcoder.com/practice/34a597ee15eb4fa2b956f4c595f03218
#include <cctype>
#include <iostream>
#include <bits/stdc++.h>
#include <vector>
using namespace std;
vector<string> add_(string s){
vector<string> vec;
string tmp;
for (int i = 0; i < s.size(); i++) {
if (i == s.size() - 1 ) {
tmp += s[i];
vec.push_back(tmp);
}
if (s[i] == '.' && !tmp.empty()) {
vec.push_back(tmp);
tmp = "";
} else {
tmp += s[i];
}
}
return vec;
}
bool check_(vector<string> vec) {
//四个部分
if (vec.size() != 4) {
return false;
}
for (auto it : vec) {
//数字
for (auto ch : it) {
if (!isdigit(ch))
return false;
}
//0在数字前
int num_index = 0;
if (it.size() > 1) {
for (auto ch : it) {
if (ch == '0' && num_index == 0)
return false;
if (ch != '0')
num_index = 1;
}
}
if (stoi(it) < 0 || stoi(it) > 255)
return false;
}
return true;
}
bool check_mask(vector<string> vec){
string tmp;
for (auto it : vec){
int n = stoi(it);
bitset<8> foo(n);
tmp += foo.to_string();
}
int num_index = 0;
for (auto it : tmp){
if (it != '1')
num_index = 1;
if (it == '1' && num_index == 1)
return false;
}
return true;
}
bitset<32> erwei(vector<string> v){
string str = "";
for (auto it : v){
int n = stoi(it);
bitset<8> foo(n);
str += foo.to_string();
}
//cout << str.size();
//long long m = stol(str);
bitset<32> foo(str);
//cout << foo<<endl;
return foo;
}
bool check_ip(vector<string> v_m,vector<string> v_1,vector<string> v_2){
bitset<32> foo_1 = erwei(v_1);
bitset<32> foo_2 = erwei(v_2);
bitset<32> foo_m = erwei(v_m);
if ((foo_1 & foo_m ) == (foo_2 & foo_m ))
return true;
return false;
}
int main() {
string mask, ip_1, ip_2;
while (cin >> mask >> ip_1 >> ip_2){
int index = 0;
vector<string> v_m = add_(mask);
vector<string> v_1 = add_(ip_1);
vector<string> v_2 = add_(ip_2);
if (!check_(v_1) || !check_(v_2) || !check_(v_m) || !check_mask(v_m)){
cout<<'1'<<endl;
continue;
}
if (check_ip(v_m, v_1, v_2)){
cout<<"0"<<endl;
continue;
}
cout << '2'<<endl;
}
}
// 64 位输出请用 printf("%lld")
上海得物信息集团有限公司公司福利 1188人发布
查看16道真题和解析