Chinaunix首页 | 论坛 | 博客
  • 博客访问: 88263
  • 博文数量: 60
  • 博客积分: 4002
  • 博客等级: 中校
  • 技术积分: 645
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-17 18:11
文章分类

全部博文(60)

文章存档

2011年(60)

我的朋友

分类: C/C++

2011-04-13 10:17:07


a:除法 b:移位 c:减法(一下子不好想到) d:穷举 e:穷举(直接查表,速度快)

  1. #include <stdio.h>

  2. int Count1(char v);
  3. int Count2(char v);
  4. int Count3(char v);
  5. int Count4(char v);
  6. int Count5(char v);

  7. int
  8. main(void)
  9. {
  10.         char v = 0x04;

  11.         printf("count1 = %d\n", Count1(v));
  12.         printf("count2 = %d\n", Count2(v));
  13.         printf("count3 = %d\n", Count3(v));
  14.         printf("count4 = %d\n", Count4(v));
  15.         printf("count5 = %d\n", Count5(v));

  16.         return (0);
  17. }

  18. /*
  19.  * a
  20.  */
  21. int
  22. Count1(char v)
  23. {
  24.         int num = 0;
  25.         while (v) {
  26.                 if (v % 2 == 1) {
  27.                         ++num;
  28.                 }
  29.                 v /= 2;
  30.         }
  31.         return (num);
  32. }

  33. /*
  34.  * b
  35.  */
  36. int
  37. Count2(char v)
  38. {
  39.         int num = 0;
  40.         while (v) {
  41.                 num += v & 0x01;
  42.                 v >>= 1;
  43.         }
  44.         return (num);
  45. }

  46. /*
  47.  * c
  48.  */
  49. int
  50. Count3(char v)
  51. {
  52.         int num = 0;
  53.         while (v) {
  54.                 v &= (v-1);
  55.                 ++num;
  56.         }
  57.         return (num);
  58. }

  59. /*
  60.  * d
  61.  */
  62. int
  63. Count4(char v)
  64. {
  65.         int num = 0;
  66.         switch (v) {
  67.                 case 0x00: num = 0; break;
  68.                 //...
  69.         }
  70.         return (num);
  71. }

  72. /*
  73.  * e
  74.  */
  75. int
  76. Count5(char v)
  77. {
  78.         int countTable[256] =
  79.                 {
  80.                 //...
  81.                 };
  82.         return (0);
  83. }

阅读(541) | 评论(0) | 转发(0) |
0

上一篇:shell启动过程

下一篇:没有了

给主人留下些什么吧!~~