华为机试:整数与IP地址间的转换

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

long long ip_to_num (string ip) {
    string str[4];
    int i = 0;
    for (char ch : ip) {
        if (ch == '.') {
            i++;
            continue;
        }
        str[i].push_back(ch);
    }
    long long ip_10 = 0;
    int bit = 24;
    for (int j = 0; j < i + 1; j++) {
        ip_10 += stoll(str[j]) << bit;
        bit -= 8;
    }
    return ip_10;
}
string num_to_ip (long long IP) {
    long long IP_10 = 0;
    int bit = 24;
    string ans;
    for (int j = 0; j < 4; j++) {
        IP_10 = IP >> bit;
        IP -= IP_10 << bit;
        ans += to_string(IP_10);
        ans += ".";
        bit -= 8;
    }
    ans.pop_back();
    return ans;
}

int main() {
    // int a, b;
    // while (cin >> a >> b) { // 注意 while 处理多个 case
    //     cout << a + b << endl;
    // }
    string ip;
    cin >> ip;
    cout << ip_to_num(ip) << endl;
    long long IP;
    cin >> IP;
    cout << num_to_ip(IP) << endl;
}

全部评论

相关推荐

暮雨轻歌:看起来hr不能接受我菜查看图片
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客企业服务