文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>两个C编程题

两个C编程题

时间:2010-03-15  来源:jy01649210

/**
*输入一个正整数,输出该数2进制位中1的个数,复杂度O(logn)
*/
unsigned int count_bit_1(unsigned int x)
{
    int matrix[5] = {
        0x55555555,
        0x33333333,
        0x0f0f0f0f,
        0x00ff00ff,
        0x0000ffff
    };
    int shift,i;
    for(i = 0,shift = 1; i < 5; i++,shift*=2)
    {
        x = (x & matrix[i]) + ((x >> shift) & matrix[i]);
    }
    return x;
}


/**
* 实现栈的push,pop,min操作,要求时间复杂度为O(1)
*/

typedef struct nod node;
struct nod
{
    int data;
    int min;
    node *prev;
};

node *head = NULL;

void push(int d)
{
    node *p;
    if(head == NULL)
    {
        head = (node *)malloc(sizeof(node));
        head->data = d;
        head->min = d;
        head->prev = NULL;
        return;
    }
    p = (node *)malloc(sizeof(node));
    p->data = d;
    if(d < head->min)
        p->min = d;
    else
        p->min = head->min;
    p->prev = head;
    head = p;
}

int pop()
{
    node *p;
    int d;
    if(head == NULL)
    {printf("empty stack\n"); exit(1);}
    p = head;
    head = head->prev;
    d = p->data;
    free(p);
    p = NULL;
    return d;
}

int min()
{
    if(head == NULL)
    {printf("empty stack\n"); exit(1);}
    return head->min;
}


相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载