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

整数与IP地址间的转换

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

/*
解题思路:十进制与二进制的互相转换,注意:十进制数转二进制数之后要补足8位再拼接
*/

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

string DecimaltoBinary(long long x){
    string res = "";
    while(x){
        int temp = x % 2;
        res = to_string(temp) + res;
        x >>= 1;
    }
    if(res.size() < 8){
        string tmp = res;
        int n = 8 - res.size();
        res = "";                                   
        while(n--){
            res += '0';
        }
        res += tmp;
    }
    return res;
}

long long BinarytoDecimal(string x){
    int len = x.size();
    long long res = 0;
    int i = 0;
    while(len--){
        int bit = x[i++] - '0';
        res += bit * pow(2, len);
    }
    return res;
}

long long IPtoDecimal(string input){
    istringstream iss(input);
    vector<int> v;
    string seg;
    while(getline(iss, seg, '.')){
        v.push_back(stoi(seg));
    }
    string tmp = "";
    for(int val : v){
        tmp += DecimaltoBinary(val);
    }
    long long ans = BinarytoDecimal(tmp);
    return ans;
}

string DecimaltoIP(long long input){
    string ans = "";
    string tmp = DecimaltoBinary(input);
    int len = tmp.size();
    int n = 32 - len;
    string temp = tmp;
    tmp = "";
    while(n--){
        tmp += '0';
    }
    tmp += temp;
    vector<string> v;
    string s = "";
    for(int i = 0; i < tmp.size(); i++){
        s += tmp[i];
        if(s.size() % 8 == 0){
            v.push_back(s);
            s = "";
        }
    }
    for(string x : v){
        long long c = BinarytoDecimal(x);
        ans += to_string(c);
        ans += '.'; 
    }
    ans.pop_back();
    return ans;
}

int main() {
    string inputs;
    cin >> inputs;
    long long inputn;
    cin >> inputn;

    long long ans1 = IPtoDecimal(inputs);
    string ans2 = DecimaltoIP(inputn);

    cout << ans1 << endl << ans2 << endl;
    
    return 0;
}

全部评论

相关推荐

03-09 20:32
运营
牛客972656413号:成绩管理系统会不会有点太。。。
点赞 评论 收藏
分享
醉蟀:你是我今年见过的最美牛客女孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务