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

整数与IP地址间的转换

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

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

unsigned long ipStrToNum(const string& ipStr) {
    string substr;//ip每一段的数字字符串
    unsigned long n = 0;//ip对应的整数
    for (int i = 0; i < ipStr.size() + 1; i++) {
        char c;
        if (i < ipStr.size())
            c = ipStr[i];
        if (i == ipStr.size() || c == '.') {

            n *= 256;
            n += stoi(substr);

            substr.clear();
        }
        else {
            substr.append(1, c);
        }
    }
    return n;
}

string numToIpStr(unsigned long n) {
    string ipStr;
    stack<int> remainder;
    unsigned long t;
    while (n) {
        t = n / 256;
        remainder.push(n - t * 256);
        n = t;
    }
    while (!remainder.empty()) {
        ipStr.append(to_string(remainder.top()));
        ipStr.append(1, '.');
        remainder.pop();
    }
    return ipStr.substr(0, ipStr.size() - 1);//去除最后多余的点字符
}

int main() {
    string ipStr;
    cin>>ipStr;
    unsigned long ipNum;
    cin>>ipNum;
    cout << ipStrToNum(ipStr) << endl;
    cout << numToIpStr(ipNum) << endl;
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务