6.3号 华为校招实习笔试题—ip转换
笔试第一题:ip转换
第一题:就是一个ip地址十进制转十六进制
输入:192.168.1.1
输出:C0.A8.1.1
思路:暴力法解决了这个问题,暂时没发现bug
#include <iostream>
#include <string>
#include <vector>
using namespace std;
char show[16] = { '0','1','2','3','4','5','6','7','8', '9','a','b','c', 'd','e','f' };
string t2h(string t)
{
int num = 0;
string result;
int first = 0;
int second = 0;
int i = 0;
for (int j = 0; j < t.size()+1; j++)
{
if (t[j] == '.' || t[j] == '\0' )
{
++i;
first = num / 16;
second = num % 16;
if (first != 0)
{
result.push_back(show[first]);
result.push_back(show[second]);
if (i<=3)
result.push_back('.');
}
else
{
result.push_back(show[second]);
if (i <= 3)
{
result.push_back('.');
}
}
num = 0;
}
else
{
num = (t[j] - '0') + num * 10;
}
}
return result;
}
int main(int argc, char* argv[])
{
string s;
cin >> s;
if (s[0] == '.')
return -1;
string res = t2h(s);
cout << "result is : " << res<< endl;
system("pause");
return 0;
}