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

整数与IP地址间的转换

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

#include <cstdio>
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
#include <cmath>
using namespace std;

unsigned int toDecimal(vector<int>& ipAddress){
    unsigned int res = 0;
    for(int i= 0; i < ipAddress.size(); ++i){
        res += ipAddress[i] * pow(2, 24-8*i);
    }
    return res;
}

string toIPAddress(unsigned int decimal){
    vector<unsigned int> tmp(4, 0);
    for(int i = 3; i >= 0; --i){
        tmp[i] = decimal & 0xff;
        decimal >>= 8;
    }
    string res;
    for(unsigned int i : tmp){
        res += to_string(i) + '.';
    }
    res.erase(res.size()-1);
    return res;
}

int main(int argc, char* argv[]){
    vector<int> ipAddress(4, 0);
    for(int i = 0; i < 4; ++i){
        string str;
        if(i != 3){
            getline(cin, str, '.');
        }
        else{
            getline(cin, str);
        }
        ipAddress[i] = stoi(str);
    }
    unsigned int decimal;
    cin >> decimal;

    cout << toDecimal(ipAddress) << endl;
    cout << toIPAddress(decimal) << endl;

    return 0;
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务