题目描述
原理:ip地址的每段可以看成是一个0-255的整数,把每段拆分成一个二进制形式组合起来,然后把这个二进制数转变成一个长整数。
举例:一个ip地址为10.0.3.193
每段数字 相对应的二进制数
10 00001010
0 00000000
3 00000011
193 11000001
组合起来即为:00001010 00000000 00000011 11000001,转换为10进制数就是:167773121,即该IP地址转换后的数字就是它了。
输入描述:
1 输入IP地址
2 输入10进制型的IP地址
输出描述:
1 输出转换成10进制的IP地址
2 输出转换后的IP地址
示例1
输入
10.0.3.193
167969729
输出
167773121
10.3.3.193
说明:
字符串部分:提取数字;基于按8位分割,也就是256进制;
数字部分:对256不断取余,利用栈先进后出的特性,控制读数的次序。
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<stdlib.h>//调用atoi函数
#include<stack>
using namespace std;
//注意数值范围long
long ipToTen(string s)
{
stack<string> st0;
string sub_s;
int pos=s.find('.');
while(pos!=-1)
{
st0.push(s.substr(0,pos));
s=s.substr(pos+1);
pos=s.find('.');
}
st0.push(s);//最后一个子串不含‘.’,如193
long t=1, sum=0;
while(!st0.empty())
{
int n=atoi(st0.top().c_str());//巧妙利用atoi函数字符串转换成数字。
st0.pop();
sum+=n*t;
t*=256;
}
return sum;
}
void TenToIp(long n)
{
stack<int> st;
while(n)
{
st.push(n%256);
n/=256;
}
for(int i=3;i>=0 && !st.empty();i--)
{
cout<<st.top();
st.pop();
if(i>0)
cout<<'.';
else
cout<<endl;
}
}
int main()
{
string s;
long n;
while(cin>>s>>n)
{
cout<<ipToTen(s)<<endl;
TenToIp(n);
}
return 0;
}