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

整数与IP地址间的转换

https://www.nowcoder.com/practice/66ca0e28f90c42a196afd78cc9c496ea?tpId=37&tags=&title=&difficulty=0&judgeStatus=0&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D37%26type%3D37

/*
思路:
    1. ip转整数
        a. 以 '.' 来分割ip字符串
        b. 分割后的字符串转成数字存在vector<size_t>数组中
        c. 通过 左移 与 或运算 得到整数
    2. 整数转ip
        a. 通过对整数进行 与运算 和 右移, 得到四个数字
        b. 通过 to_string 把四个数字转换为字符串
        c. 拼接ip字符串
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
// 以 '.' 来分割ip字符串
size_t ipToStr(string str){
    vector<size_t> v;
    int pos = str.find_first_of('.');
    string tmp = str.substr(0, pos);
    v.push_back(stoi(tmp));

    str = str.substr(pos+1);
    pos = str.find_first_of('.');
    v.push_back(stoi(str.substr(0, pos)));

    str = str.substr(pos+1);
    pos = str.find_first_of('.');
    v.push_back(stoi(str.substr(0, pos)));

    str = str.substr(pos+1);
    pos = str.find_first_of('.');
    v.push_back(stoi(str.substr(0, pos)));

    size_t ipInt = v[0] << 24 | v[1] << 16 | v[2] << 8 | v[3];

    return ipInt;
;
}

string numToIP(size_t str){
    string ans;
    size_t ipNum = (str);

    ans += to_string((ipNum >> 24) & 0xff);
    ans.append(1, '.');
    ans += to_string((ipNum >> 16) & 0xff);
    ans.append(1, '.');

    ans += to_string((ipNum >> 8) & 0xff);
    ans.append(1, '.');
    ans += to_string((ipNum >> 0) & 0xff);

    return ans;
}


int main() {
    string ip;
    size_t num;
    cin >> ip;
    cin >> num;

    cout << ipToStr(ip) << endl;
    cout << numToIP(num) << endl;

    return 0;
}
// 64 位输出请用 printf("%lld")

全部评论
函数ipToStr 还可以再优化一下
点赞 回复 分享
发布于 2024-10-10 10:00 浙江

相关推荐

头像
03-20 22:00
重庆大学 Java
适彼乐土:“他们不行再找你” 最后的底牌吗?有点意思
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务