数组中值为2的n次幂的元素个数

刚开始想到的是用2个for循环,外层用2的n次幂,内层用数组,去比对,如果相等则统计值++。后来想到无法判断n的界限,想要获知n的界限还要知道数组的最大值,就牵扯到数组的排序了。

理顺思路后,分拆一下解题步骤,第一步对数组排序,使数组单调递增;第二步判断2的n次幂个数。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

void bubblesort(int *array, unsigned int len)
{
    int i, j, tmp;

    if (NULL == array) {
        return;
    }

    for (i=0; i<len; i++) {
        for (j=i+1; j<len; j++) {
            if (array[i] > array[j]) {
                tmp = array[i];
                array[i] = array[j];
                array[j] = tmp;
            }            
        }
    }
}

int pow_num(int *array, unsigned int len)
{
    int i, n, power, count = 0;

    if (NULL == array) {
        return -1;
    }

    for (i=0, n=0; i<len;) {
        power = 1 << n;

        if (array[i] == power) {
            count++;
            i++;
        } else if (array[i] < power) {
            i++;
        } else {
            n++;
        }
    }

    return count;
}


int main(int argc, char *argv[])
{
    int i, n, power, count = 0;
    unsigned int len;
    int *vector = NULL;

    /* get the array lenth from input */
    scanf("%u", &len);

    vector = (int *)malloc(len * sizeof(int));
    if (NULL == vector) {
        return 1;
    }
    /* get the array value from input  */
    for (i=0; i<len; i++) {
        scanf("%d", &vector[i]);
    }

    /* function call */
    bubblesort(vector, len);
    printf("%d", pow_num(vector, len));

    free(vector);
    return 0;
}

发布了27 篇原创文章 · 获赞 2 · 访问量 4625

猜你喜欢

转载自blog.csdn.net/xqjcool/article/details/49794103