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

整数与IP地址间的转换

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

#include <cstdlib>
#include <iostream>
using namespace std;

long ip2long(const string& ip)
{
    const char* s = ip.c_str();
    char* endptr = nullptr;
    long value = 0;
    for (int i = 0; i < 4; ++i) {
        auto v = strtol(s, &endptr, 10);
        s = endptr + 1;
        value = (value << 8) + v;
    }
    return value;
}

string long2ip(const long value)
{
    int c1 = value >> 24;
    int c2 = (value >> 16) & 0xFF;
    int c3 = (value >> 8) & 0xFF;
    int c4 = value & 0xFF;
    char ip[16] = {'\0'};
    snprintf(ip, sizeof(ip), "%d.%d.%d.%d", c1, c2, c3, c4);
    return string{ip};
}

int main() {
    string ip;
    long value;
    while (cin >> ip >> value) {
        cout << ip2long(ip) << endl;
        cout << long2ip(value) << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

05-07 19:10
已编辑
中国科学技术大学 C++
silly01:现在先去 momenta,8-9月去鹅找日常实习,八股文算法背好了你这随便进。不过建议补充一下后端知识,MySQL、Redis看下八股,再补个6824,加点go后台的技术栈,9月随便进大厂。CPP后端只能来WXG
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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