厚积薄发,滴水穿石

搬家到主站了:http://www.cnblogs.com/cokecoffe/
随笔 - 45, 文章 - 8, 评论 - 12, 引用 - 0
数据加载中……

几个弱智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;

}


posted on 2012-05-05 20:00 Wangkeke 阅读(690) 评论(0)  编辑 收藏 引用 所属分类: C


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理