题目 : 输入一组IPv4地址,返回子网掩码的最大子网掩码长度(二进制中表示的掩码中“1” 的个数)
例子:
输入:“192.168.129.7”,“192.168.206.155”
输出:17
#include <iostream>
#include <string>
#include <bitset>
#include <vector>
#include <algorithm>
using namespace std;
vector<string> getBinaryOctets(const string& ipAddress) {
vector<string> octets;
string octet;
for (int i = 0; i < ipAddress.size(); i++) {
if (ipAddress[i] == '.') {
octets.push_back(octet);
octet.clear();
} else {
octet += ipAddress[i];
}
}
octets.push_back(octet);
return octets;
}
int getMaxSubnetMaskLength(const vector<string>& ipAddresses) {
vector<vector<string>> binaryOctets(ipAddresses.size());
for (int i = 0; i < ipAddresses.size(); i++) {
binaryOctets[i] = getBinaryOctets(ipAddresses[i]);
}
int minSubnetMaskLength = INT_MAX;
for (int i = 0; i < 4; i++) {
vector<int> binaryValues;
for (int j = 0; j < binaryOctets.size(); j++) {
binaryValues.push_back(stoi(binaryOctets[j][i], nullptr, 2));
}
sort(binaryValues.begin(), binaryValues.end());
int subnetMaskLength = 0;
for (int j = 0; j < 8; j++) {
if ((binaryValues[0] >> (7 - j)) == (binaryValues[binaryValues.size() - 1] >> (7 - j))) { // 对比排序后开始与最后一组IP的字节位
subnetMaskLength++;
} else {
break;
}
}
minSubnetMaskLength = min(minSubnetMaskLength, subnetMaskLength);
}
return minSubnetMaskLength;
}
int main() {
vector<string> ipAddresses = {"192.168.0.1", "192.168.0.2", "192.168.0.3", "192.168.0.4"};
int maxSubnetMaskLength = getMaxSubnetMaskLength(ipAddresses);
cout << "Max subnet mask length: /" << maxSubnetMaskLength << endl;
return 0;
}
使用位操作比较二进制值:
int getMaxSubnetMaskLength(vector<string> ipAddresses) {
int subnetMaskLength = 0;
for (int i = 0; i < 32; i++) {
int bitValue = 1 << (31 - i);
bool allBitsEqual = true;
for (int j = 1; j < ipAddresses.size(); j++) {
int binaryValue1 = htonl(inet_addr(ipAddresses[j-1].c_str()));
int binaryValue2 = htonl(inet_addr(ipAddresses[j].c_str()));
if ((binaryValue1 & bitValue) != (binaryValue2 & bitValue)) {
allBitsEqual = false;
break;
}
}
if (allBitsEqual) {
subnetMaskLength++;
} else {
break;
}
}
return subnetMaskLength;
}
使用Python中的iPaddress模块:
import ipaddress
def getMaxSubnetMaskLength(ipAddresses):
subnets = [ipaddress.IPv4Address(ip) for ip in ipAddresses]
subnet = ipaddress.collapse_addresses(subnets)[0]
return subnet.prefixlen