华为oj中级 整数与IP地址之间的转换

来源:互联网 发布:我的世界mac存档放哪 编辑:程序博客网 时间:2024/05/20 19:45

描述
原理:ip地址的每段可以看成是一个0-255的整数,把每段拆分成一个二进制形式组合起来,然后把这个二进制数转变成
一个长整数。
举例:一个ip地址为10.0.3.193
每段数字 相对应的二进制数
10 00001010
0 00000000
3 00000011
193 11000001
组合起来即为:00001010 00000000 00000011 11000001,转换为10进制数就是:167773121,即该IP地址转换后的数字就是它了。

的每段可以看成是一个0-255的整数,需要对IP地址进行校验

知识点 字符串,位运算
运行时间限制 10M
内存限制 128
输入
输入
1 输入IP地址
2 输入10进制型的IP地址
输出
输出
1 输出转换成10进制的IP地址
2 输出转换后的IP地址
样例输入 10.0.3.193 167969729
样例输出 167773121 10.3.3.193

#include<iostream>#include<algorithm>#include<string>#include<vector>#include<unordered_map>#include<fstream>#include<sstream>#include<queue>#include<stack>using namespace std;void test1(string &s){    unsigned long int a, b, c, d;    string str;    int pos;    pos = s.find(".");    a=stol(s.substr(0, pos))<<24;    s = s.substr(pos + 1);    pos = s.find(".");    b = stol(s.substr(0, pos)) << 16;    s = s.substr(pos + 1);    pos = s.find(".");    c = stol(s.substr(0, pos)) << 8;    s = s.substr(pos + 1);    d = stol(s);    cout << (a + b + c + d) << endl;}void test2(unsigned long int &n){    unsigned long int a, b, c, d;    d = n & 0xff;    c = (n >> 8) & 0xff;    b = (n >> 16) & 0xff;    a = (n >> 24) & 0xff;    cout << a << "." << b << "." << c << "." << d << endl;}int main(){    string s;    unsigned long int num;    while (cin>>s>>num){        test1(s);        test2(num);    }    return 0;}
0 0