#include "stdio.h"
#include "stdlib.h"
#include "string.h"

// 时间原因只做三星以上
/*********
* 2.65
*********/
int even_ones(unsigned x)
{
    x ^= (x>>16);
    x ^= (x>>8);
    x ^= (x>>4);
    x ^= (x>>2);
    x ^= (x>>1);
    return !(x&1);
}

/*********
* 2.66
* hint: construct a bit vector like [0...01..111]
*********/
int leftmost_one(unsigned x)
{
    x |= (x>>1);
    x |= (x>>2);
    x |= (x>>4);
    x |= (x>>8);
    x |= (x>>16);
    return x&(~(x>>1));
}

/*********
* 2.69
*********/
unsigned rotate_right(unsigned x, int n)
{
    return (x>>n)+(x<<(32-n));
}

int main(int argc, char *argv[])
{
    unsigned x = 16;

    if(argc > 1)
    {
        x = (unsigned)strtol(argv[1], NULL, 0);
    }
    else 
        printf("default value of x is 16\n");

    printf("dec value of x: %d\n", x);
    printf("hex value of x: 0x%x\n------------------\n", x);

    printf("even_ones(%d)= %d\n", x, even_ones(x));
    printf("leftmost_one(%d)= 0x%x\n", x, leftmost_one(x));
    int n = 4;
    if( argc > 2 )
        n = strtol(argv[2], NULL, 0);
    printf("rotate_right(%d, %d)= 0x%x\n", x, n, rotate_right(x, n));    
    return 0;
}

Sisyphus
2 声望1 粉丝

引用和评论

0 条评论