欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

华为笔试: 判断两个IP是否为同一网段(c/c++实现)

程序员文章站 2022-06-09 11:09:59
...
问题描述:

判断两个Ip是否为同一个网段: Ip1,Ip2分别与子网淹Ip3进行与操作,结果相同则判断为同一个网段,输出结构:1 与操作结果; 否则输出0;

#include 
#include
#include
#define Length 4
using namespace std;

void printIntArray(int * array){
    for ( int i = 0; i < Length; i++ )
        cout << array[i] << "  ";
    cout << endl;
}

int charToInt(char ch, int sum){
    int result = sum * 10 + ( ch - '0' );
    return result;
}

void getIntOfIp(char * ip, int * intArray){
    int count = 0;
    int temp = 0;
    while ( *ip != '\0' ){

        if ( *ip == '.' ){
            intArray[count] = temp;
            count ++;
            temp = 0;    
        }else if ( count == 0 ){
            temp = charToInt(*ip, temp);
        }else if ( count == 1 ){
            temp = charToInt(*ip, temp);
        }else if ( count == 2 ){
            temp = charToInt(*ip, temp);
        }else if ( count == 3 ){
            temp = charToInt(*ip, temp);
        }
        ip++;
    }
    intArray[count] = temp;
}

void ipAndSubIP(int * nums1,int * nums2,int *nums3){
    for ( int i = 0; i < Length; i++ ){
        nums3[i] = nums1[i] & nums2[i];
    }
}

bool compareInt(int * nums1, int * nums2){
    for ( int i = 0; i < Length; i++ ){
        if ( nums1[i] - nums2[i] )
            return false;
    }
    return true;
}

void getFlagToString(int * nums,char * ch){
    int count = 0;
    for ( int i = 0; i < Length; i++ ){
        int num = nums[i];
        int getH = num/100;
        int getM = num / 10 % 10;
        int getL = num % 10;
        if ( getH ){
            ch[count++] = getH + '0';
            ch[count++] = getM + '0';
        } else if ( getM ){
            ch[count++] = getM + '0';
        }
        ch[count++] = getL + '0';
        ch[count++] = '.';
    }
    ch[count-1] = '\0';
}

bool getResult(char *ip1, char * ip2, char * ip3, char * ch){
    // 取出ip的整数值
    int ip1Array[Length],ip2Array[Length],ip3Array[Length],flag1Array[Length], flag2Array[Length];
    getIntOfIp(ip1, ip1Array);
    getIntOfIp(ip2, ip2Array);
    getIntOfIp(ip3, ip3Array);

    ipAndSubIP(ip1Array, ip3Array, flag1Array);
    ipAndSubIP(ip2Array, ip3Array, flag2Array);

    bool result = compareInt(flag1Array, flag2Array);

    if ( result ){
        getFlagToString(flag1Array, ch);
    }
}

int main(void){

    // 输入两个ip, 一个子网言马
    char ip1[13],ip2[13], ip3[13];
    cin >> ip1 >> ip2 >> ip3;

    // 判断ip与子网淹马的&是否相等,不相等输出0; 相等时,输出1, 并输出&后的值
    char ch[13];
    bool result = getResult( ip1 , ip2, ip3, ch);
    if ( result ){
        cout << "1 " << ch << endl;
    }else {
        cout << "0" << endl;
    }
    return 0;
}

相关标签: 笔试