题解 | #整数与IP地址间的转换#

整数与IP地址间的转换

http://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea

/*
**直接用stoi和to_string函数强撸
*/
#include <iostream>
#include <string>

using namespace std;

int main(void)
{
    string s;
    unsigned int ip;
    while(cin >> s >> ip)
    {
        unsigned int t[4] = {0};
        string v[4];
        unsigned int oip = 0;
        int j = 0;
        for (int i = 0; i < s.size();i++)
        {
            if(s[i] == '.')
            {
                j++;
            }
            else
            {
                v[j] += s[i];
            }
        }

        oip = stoi(v[0]) << 24 | stoi(v[1]) << 16 | stoi(v[2]) << 8 | stoi(v[3]) << 0;
        cout<< oip <<endl;

        string v1[4];
        for (j = 0; j < 4; j++)
        {
            v1[j] = to_string(((ip >> ((3 - j) * 8)) & 0xff));
            if (j == 3) cout<<v1[j] << endl;
            else cout<<v1[j] << ".";
        }


    }
    return 0;
}
全部评论

相关推荐

3 2 评论
分享
牛客网
牛客企业服务