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;
}