几个弱智C题

从网上下了一个C的笔试题,发现附带的答案,不是错的,就是很初级的人写的,发现看了半天,没看懂!于是自己写了一下

 

1.给定一个字符串,输出本字符串中只出现一次并且最靠前的那个字符的位置?

比如"abaccddeeef" 则是b,输出2

 

int find_char(const char *str)

{

   int pos[256];

   const char *p = str;

 

   if((!str)||!(*str))//空指针或者空串

   {

      return -1;

   }

 

   memset(pos,-1,sizeof(pos));

 

//遍历一遍,存下每个字母的位置,如果存过一次,就把位置设置为-2

   while (*p)

   {

      if (pos[*p] == -1)

      {

         pos[*p] = p - str;

      }

      else

      {

         pos[*p] = -2;

      }

      p++;

   }

//遍历存储字母位置的数组,如果存有位置,则返回

   p = str;

   while (*p)

   {

      if (pos[*p]>=0)

      {

         return pos[*p];

      }

      p++;

   }

 

   return -1;

}

 

2,给定一个整数,问这个整数转成2进制后,里面包含有多少个1?比如:10,二进制表示为,1010则,输出2

int howmany(int x)

{

   int count = 0;

   while (x)

   {

      if ((x&1) == 1)

      {

         count++;

      }

      x = x>>1;

   }

   return count;

}

 



Wangkeke 2012-05-05 20:00 发表评论

posted on 2012-05-05 20:00  cokecoffe  阅读(176)  评论(0编辑  收藏  举报

导航