華爲機試—整數與IP地址間的轉換

題目描述
原理:ip地址的每段可以看成是一個0-255的整數,把每段拆分成一個二進制形式組合起來,然後把這個二進制數轉變成一個長整數。
舉例:一個ip地址爲10.0.3.193
每段數字 相對應的二進制數
10 00001010
0 00000000
3 00000011
193 11000001
組合起來即爲:00001010 00000000 00000011 11000001,轉換爲10進制數就是:167773121,即該IP地址轉換後的數字就是它了。

輸入描述:
1 輸入IP地址
2 輸入10進制型的IP地址

輸出描述:
1 輸出轉換成10進制的IP地址
2 輸出轉換後的IP地址
示例1
輸入

10.0.3.193
167969729

輸出

167773121
10.3.3.193

說明:
字符串部分:提取數字;基於按8位分割,也就是256進制;
數字部分:對256不斷取餘,利用棧先進後出的特性,控制讀數的次序。

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<stdlib.h>//調用atoi函數
#include<stack>
using namespace std;
//注意數值範圍long
long ipToTen(string s)
{
    stack<string> st0;
    string sub_s;
    int pos=s.find('.');
    while(pos!=-1)
    {
        st0.push(s.substr(0,pos));
        s=s.substr(pos+1);
        pos=s.find('.');
    }
    st0.push(s);//最後一個子串不含‘.’,如193

    long t=1, sum=0;
    while(!st0.empty())
    {
        int n=atoi(st0.top().c_str());//巧妙利用atoi函數字符串轉換成數字。
        st0.pop();

        sum+=n*t;
        t*=256;
    }
    return sum;
}
void TenToIp(long n)
{
    stack<int> st;
    while(n)
    {
        st.push(n%256);
        n/=256;
    }

    for(int i=3;i>=0 && !st.empty();i--)
    {
        cout<<st.top();
        st.pop();
        if(i>0)
            cout<<'.';
        else
            cout<<endl;
    }
}

int main()
{
    string s;
    long n;
    while(cin>>s>>n)
    {
        cout<<ipToTen(s)<<endl;
        TenToIp(n);
    }   
    return 0;
}
發佈了56 篇原創文章 · 獲贊 12 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章