#include <iostream>
using namespace std;
#include <string>
#include <sstream>
unsigned str2us(string str) {
string num;
unsigned b;
istringstream bmCode(str);
while (getline(bmCode, num, '.')) {
b = (b << 8) + stoi(num);
}
return b;
}
bool ipScan(string str) {
string num;
istringstream is(str);
while (getline(is, num, '.')) {
if (stoi(num) > 255 || stoi(num) < 0) {
return false;
}
}
return true;
}
bool bmScan(unsigned b) {
if (!b) {
return false;
}
b = ~b + 1;
if (b == 1) {
return false;
}
if ((b & (b - 1)) == 0) {
return true;
}
return false;
}
int main() {
string bmCode;
string ip1;
string ip2;
getline(cin, bmCode);
getline(cin, ip1);
getline(cin, ip2);
unsigned bm = str2us(bmCode);
if (!ipScan(ip1) || !ipScan(ip2) || !bmScan(bm)) {
cout << "1" << endl;
return 0;
}
unsigned uip1 = str2us(ip1);
unsigned uip2 = str2us(ip2);
unsigned result1 = uip1 & bm;
unsigned result2 = uip2 & bm;
if (result1 == result2) {
cout << "0" << endl;
} else {
cout << "2" << endl;
}
}
https://www.nowcoder.com/discuss/459763190767869952?sourceSSR=users
基本上复用HJ18的代码就ok了
主要还是对子网掩码是否合法的判断,还有地址向数字的判断

京公网安备 11010502036488号