AcWing 3634. IP地址
原题链接
简单
作者:
cwn
,
2024-01-14 17:44:49
,
所有人可见
,
阅读 47
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
bool check(string s)
{
int cnt = 0;
int cnt1 = 0;
for(int i=0;i<s.size();i++)
{
if(isalpha(s[i])) return false;
if(s[i] == '.') cnt++;
if(isdigit(s[i]))
{
cnt1++;
int j = i;
int x = 0;
while(j<s.size() && isdigit(s[j]))
{
x = x * 10 + s[j] - '0';
j++;
}
if(x > 255) return false;
i = j - 1;
}
if(s[i] != '.' && !isdigit(s[i]) && !isalpha(s[i])) return false;
}
if(cnt != 3 || cnt1 != 4) return false;
return true;
}
string trans(int n)
{
int x = 0;
string ss,c;
if(n == 0) ss = "0";
while(n != 0)
{
x = n % 16;
if(x<10) c = x + '0';
else
{
c = x + 'A' - 10;
}
ss = c + ss;//逆序
n = n / 16;
}
return ss;
}
int main()
{
string s;
cin>>s;
string anss = "0x";
if(check(s))
{
for(int i=0;i<s.size();i++)
{
if(isdigit(s[i]))
{
int j = i;
int x = 0;
while(j<s.size() && isdigit(s[j]))
{
x = x * 10 + s[j] - '0';
j++;
}
i = j - 1;
string ss = trans(x);
//cout<<ss<<endl;
if(ss.size()<2) ss = '0' + ss;
//cout<<ss<<endl;
anss += ss;
}
}
cout<<anss<<endl;
}
else
{
cout<<"Error"<<endl;
}
return 0;
}