2008年5月17日星期六

編程趣題

不計"開blog了"的文章,最多回應便是有c語言的那一篇, 哈哈,
再來說清楚一下吧,

int a[10]; //a is an array of ten integer
int* b[10];//b is an array of ten integer pointer
int (*c)[10];//c is a pointer to an array of the integer
int (*(*d)(char))[]; //What is d ?

先開估︰
d is a pointer to a function which take a char argument and returning a pointer to an array of integer.

長長的答案,應該沒有錯吧?請各位親見下手寫幾行code去証實一下我的答案!
親自發掘答案你將獲益良多!
不過如果反應熱烈,我也會寫幾行code出來說明一下當中拆解的logic。
可是自己的功力尚淺, 只是藉著多點討論,交流,自己也可以進步一下!如果大家有什麼趣題,
觀迎post出來大家一起研究!

好..再來一題....
q2. write a function to calculate the number of bit '0' in the argument
for example,
input =0xFFF0, it should return 4
input =0xFF00, it should return 8

I welcome all kind of language, c/c++, java, asm...etc...

3 則留言:

  1. First time to come here. Leave leave comment sin...
    For Q.2, if you have unlimited RAM, the easiest way to achieve the task is by using table look up.
    But we are working in the embedded world so RAM=$=the less you use the better. So another solution is by shifting and doing bitwise operation. If it is a 32-bit variable you have to shift for 32 times. This is fairly simple, but yet inefficient. If you take a closer look, you can actually constuct a 256 entries table so that for a 32 bit variable you just need to perform 4 table look up.
    So what is your model answer to this question?

    回覆刪除
  2. Thanks for the sharing! I don't have "model" answer,but would like to share an interesting solution.

    int cnt_0 (unsigned int n) {
    int count =0 ;
    n ^= 0xFFFFFFFF;
    while (n)
    {
    count++ ;
    n &= (n - 1) ;
    }
    return count ;
    }
    If we loop for every bit, it is O(n). This solution only loop for the number of bit0,
    i.e. run proportional to the number of bit 0. May be faster,

    回覆刪除