20080306:上海华为的一道关于指针的编程题目

来源:互联网 发布:gta5 handling 数据 编辑:程序博客网 时间:2024/06/10 00:09

int A[nSize],其中隐藏着若干0,其余为非0整数,写一个函数int Func(int *A, int nSize),使A把0移至后面,非0整数移至数组前面并保持有序,返回值为原数据中第一个元素为0的下标。

这里只需要关心非0整数,下面给一个简单的实现,但把原题目中“返回原数据中的第一个元素为0的下标”改为“返回新数组中的第一个元素为0的下标”。

int FuncA(int *A, int nSize)
{
    if (NULL == A || nSize < 0)
        return -1;
    int count(0);  // 非0计数器
    for (int i(0); i < nSize; i++) {
        if(A[i] != 0) {
            //if (i > count)
            //   A[count] = A[i]
            //++count;
            A[count++] = A[i];
        }
    }
    memset(A+count, 0, nSize-count);
    return count;  // could be : count == nSize
}