从网上下了一个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;

}

 

几个弱智C题

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

相关文章:

  • 2021-10-12
  • 2021-07-15
  • 2021-11-04
  • 2022-12-23
  • 2021-10-16
  • 2021-07-05
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-03-07
  • 2021-09-04
  • 2022-12-23
  • 2021-10-28
  • 2021-09-27
  • 2021-08-28
  • 2022-02-25
相关资源
相似解决方案