C语言之面试题(三)

求x数的二进制中有多少个1

int fun(int x)
{
  int count=0;
  while(x)
{
 x=x&(x-1); //按位与操作,全为1才为1。每次-1,再与,都会少一个1
}
retun count;//返回循环次数
}

检查下面程序

#define MAX 255
int main()
{
  unsigned char A[MAX];
  unsigned char i;
  for(i=0;i<=MAX;i++)
{
  A[i]=i;
}
}

//两个错误
1.错误一:数组越界,长度为MAX的数组,标号最大为MAX-1
2.错误二:死循环。unsigned char范围为[0,255]当i加到255时,再+1,就是0。所以死循环。

快速排序算法:分治法

快速排序的思想是,从数组中随机取一个数作为基准数,然后把比这个基准数小的放在左边,比基准数大的放在右边。然后再在左右两边各自再进行用分治法,直到排序成功。

int quick_rand(const int* p,const int low,const int high)
{
   int X=p[0];
   while(low<high)
   {
     while((low<high)&&(X>p[high]))   
       high--;
       if(low<high)
       {
          p[low]=p[high];   //把p[high]的坑填在p[low]中,p[high]空了
          low++;
       } 
   
     while((low<high)&&(X<=p[low]))
       low++;
       if(low<high)
       {
          p[high]=p[low]; //把刚才的坑填满
       }
   
     s[low]=X; //来到这里时 low==high
    
        
   }
   return low;
} 

再用递归对两边实现分治:

void digui_rand(const int* str,const int low,const int low)
{
   if(low<high)
   {
   int i=quick_rand(str,low,high);
   digui_rand(str,low,i-1);    //
   digui_rand(str,i+1,high);   //
   }
}
/*前期的递归,不断让区间变小,直到low==high,之后返回上一级函数,执行真正的命令*/

就可以实现想要的功能了。 

猜你喜欢

转载自blog.csdn.net/weixin_40288381/article/details/81106687