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

整数与IP地址间的转换

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

#include <iostream>
#include <sstream>
#include <string>

using namespace std;

unsigned int ipToint(string s) {
    // 先将所有的.转换成空格
    for (auto& elem : s)
        if (elem == '.')
            elem = ' ';
    unsigned int res = 0;
    istringstream iss(s);
    unsigned int tmp;
    iss >> tmp;
    res += tmp * (1 << 24);
    iss >> tmp;
    res += tmp * (1 << 16);
    iss >> tmp;
    res += tmp * (1 << 8);
    iss >> tmp;
    res += tmp;
    return res;
}

string intToip(unsigned int n) {
    string res;
    res = "." + to_string(n % (1 << 8)) + res;
    n >>= 8;
    res = "." + to_string(n % (1 << 8)) + res;
    n >>= 8;
    res = "." + to_string(n % (1 << 8)) + res;
    n >>= 8;
    res = to_string(n % (1 << 8)) + res;
    return res;
}

int main() {
    string ips;
    cin >> ips; // 点分十进制形式的ip
    cout << ipToint(ips) << endl;
    unsigned int ipn;   // 正整数形式的ip
    cin >> ipn;
    cout << intToip(ipn) << endl;

    return 0;
}

全部评论

相关推荐

爱读书的放鸽子能手很...:刷个两端实习,冲春招,流水线什么时候不能去
我的秋招日记
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务