华为的笔试好难...

3道题过了1道基本没戏了…就做了第一道出来了,第二道过了20%。

华为的笔试好难..._第1张图片
华为的笔试好难..._第2张图片

#include 
#include 
#include 
#include 
#include 

using namespace std;

void getIp(vector<int>& data, string ip) {
	vector<char> temp;
	int val;
	int mul;
	for (int i = 0; i < ip.size(); i++) {
		if (ip[i] != '.') {
			temp.push_back(ip[i]);
		}
		else {
			val = 0;
			mul = 1;
			for (int j = temp.size() - 1; j >= 0; j--) {
				val += (temp[j] - 48) * mul;
				mul *= 10;
			}
			data.push_back(val);
			temp.clear();
		}
	}
	val = 0;
	mul = 1;
	for (int j = temp.size() - 1; j >= 0; j--) {
		val += (temp[j] - 48) * mul;
		mul *= 10;
	}
	data.push_back(val);
}

string intToString(int val) {
	string result = "";
	if (val == 0) {
		result = "0";
		return result;
	}
	while (val > 0) {
		int temp = val % 10;
		result += (temp + 48);
		val /= 10;
	}
	reverse(result.rbegin(), result.rend());
	return result;
}

int judgeTwoIp(string ip1, string ip2, string childNet, string& extra) {
	vector<int> data1;
	vector<int> data2;
	vector<int> dataChild;
	getIp(data1, ip1);
	getIp(data2, ip2);
	getIp(dataChild, childNet);
	for (int i = 0; i < dataChild.size(); i++) {
		string temp = intToString(data1[i] & dataChild[i]);
		extra += temp;
		if (i != dataChild.size() - 1)
			extra += ".";
	}
	for (int i = 0; i < dataChild.size(); i++) {
		if ((data1[i] & dataChild[i]) != (data2[i] & dataChild[i]))
			return 0;
	}
	return 1;
}

int main() {
	string ip1 = "192.168.1.1";
	string ip2 = "192.168.2.1";
	string childNet = "255.255.255.0";
	string extra = "";
	int result = judgeTwoIp(ip1, ip2, childNet, extra);
	if (result == 0)
		cout << "0 " << extra;
	else
		cout << "1 " << extra;
	system("pause");
	return 0;
}

你可能感兴趣的:(随笔)