C ++ interview questions (1)

1, list reversal

    My previous interview questions have related, do not write

2, to achieve the array function to find the second largest number (key point - the first two are saved from the greatest number come)

//找出第二大的数
int search_sec(int *arr, int len)
{
    int ret[2] = { 0,0 };
    for (int i = 0; i < len; ++i)
    {
        if (arr[i] > ret[0])
        {
            ret[1] = ret[0];
            ret[0] = arr[i];
        }
        else if (arr[i] > ret[1])
        {
            ret[1] = arr[i];
        }
    }
    return ret[1];
}

3, to achieve the function, the first 16-bit integers are summed according to a four bit per integer (test sites, shift operation )

//位运算
int test(int a)
{
    int temp;
    int count = 0;
    for (int i = 0; i < 4; ++i)
    {
        temp = a >> i * 4;
        count += temp & 0x000F;
    }
    return count;
}

4, the output request

    union
    {
        int a;
        char b[2];
    }aa;
    aa.a = 0;
    aa.b[0] = 10;
    aa.b[1] = 1;
    printf("%d",aa.a);

The output is 266

Analysis: United aa occupies four bytes sequentially in the memory 10, 1, 0, 0

It is interpreted as an int 0,0,1,10

Where 1 is 256, the output is 256 + 10

Guess you like

Origin blog.csdn.net/Think88666/article/details/92010267