当前位置: 代码迷 >> 综合 >> nowcoder 整数与IP地址间的转换(DAY 212)---- 后端面试题
  详细解决方案

nowcoder 整数与IP地址间的转换(DAY 212)---- 后端面试题

热度:14   发布时间:2023-11-17 16:40:46.0

文章目录

    • 原题题目
    • 代码实现(首刷自解)
    • 代码实现(二刷自解 DAY 318 C++)


原题题目


在这里插入图片描述


代码实现(首刷自解)


#include <iostream>
#include <string>
using namespace std;int main()
{
    string str_ip_address;string int_ip_address;while(cin >> str_ip_address >> int_ip_address){
    str_ip_address += '.';unsigned int ip_num = 0;string tmp{
    };int shift = 24;for(const auto& chr:str_ip_address){
    if(chr != '.')tmp += chr;else{
    ip_num += (static_cast<unsigned int>(stoi(tmp)) << shift);shift -= 8;tmp.clear();}}int times = 4,num = 255;shift = 24;string ip_str{
    };unsigned int int_ip_add = stoul(int_ip_address);while(times--){
    unsigned int ip_part = (int_ip_add >> shift) & num;shift -= 8;ip_str += to_string(ip_part);if(times)    ip_str += '.';}cout << ip_num << endl;cout << ip_str << endl;}return 0;
}

代码实现(二刷自解 DAY 318 C++)


#include <iostream>
#include <string>
#include <algorithm>
#include <stack>using namespace std;void AnsForNumIp(const string& ip) {
    unsigned long num = 1;for (int i = 0; i < 7; ++i) {
    num <<= 1;num += 1;}stack<string> stack;string ans;unsigned long ipnum = stoul(ip);for (int i = 0; i < 4; ++i) {
    stack.emplace(to_string(ipnum & num));ipnum >>= 8;}while (!stack.empty()) {
    ans += stack.top();stack.pop();ans += '.';}ans.pop_back();cout << ans << endl;
}void AnsForCharIP(const string& ip) {
    int tmpnum = 0;int startindex = 0, endindex = 0;unsigned long long ans = 0;for (int i = 0; i < 4; ++i) {
    while (endindex < ip.size() && ip[endindex] != '.') ++endindex;ans <<= 8;ans += stoul(ip.substr(startindex, endindex - startindex));startindex = ++endindex;}cout << ans << endl;
}int main() {
    string ipnum, nextip;cin >> ipnum >> nextip;AnsForCharIP(ipnum);AnsForNumIp(nextip);return 0;
}
  相关解决方案