一道C++笔试题(实例)
来源:优易学  2011-12-19 16:15:43   【优易学:中国教育考试门户网】   资料下载   IT书店
  题目:
  面试厦门欧乐时的一道编程题,拿出来大家共同学习一下:从1到100000中随意取出两个数,然后将其余99998个数打乱放入数组A中,现在要求遍历一次数组A,就要找到取出的那两个数。要求:最多只能定义5个变量,不能定义数组。大家有兴趣的试试。
  可以这么考虑,设那连个数为x和y,获得x+y和x*x+y*y的值,那么就可以算出x和y出来。
  x+y可以从1到100000的和减去数组之和得出,x*x+y*y可以从1到100000的平方和减去数组之平方和获得,然后就可以计算具体x和y。同理,如果找3个数,那么将要技术立方和,以此类推。
  下面是本人所写的代码。
  #include <stdio.h>
  #include <time.h>
  #include <stdlib.h>
  #include <iostream>
  #define MAX 100000
  void show(int *array,int len)
  {
  std::cout<<array[len-2]<<’\t’<<array[len-1]<<’\n’;
  return;
  for(int i=0;i<len;++i)
  {
  if(i%10==0)
  std::cout<<std::endl;
  std::cout<<array[i]<<’\t’;
  }
  std::cout<<’\n’;
  }
  int run(int *array,int len)
  {
  unsigned long expectSum=(1+len+2)*(len+2)/2;
  unsigned long expectDSum=(len+1)*(len+1)+(len+2)*(len+2);
  unsigned long arraySum=0;
  unsigned long arrayDSum=0;
  for(int i=0;i<len;++i)
  {
  expectDSum+=(i+1)*(i+1);
  arraySum+=array[i];
  arrayDSum+=array[i]*array[i];
  }
  std::cout<<"expectSum:"<<expectSum<<’\t’
  <<"expectDSum:"<<expectDSum<<’\t’
  <<"arraySum:"<<arraySum<<’\t’
  <<"arrayDSum:"<<arrayDSum<<’\n’;
  unsigned long A=expectDSum-arrayDSum;
  unsigned long B=expectSum-arraySum;
  unsigned long C=(2*A-B*B);
  std::cout<<"x+y="<<B<<’\t’
  <<"x*x+y*y:"<<A<<’\n’
  <<"2*A-B*B:"<<C<<’\n’;
  unsigned long x_y=sqrt(C);
  std::cout<<"x-y:"<<x_y<<’\n’;
  std::cout<<"x:"<<(x_y+B)/2<<’\n’;
  std::cout<<"y:"<<(B-x_y)/2<<’\n’;
  return 0;
  }
  int main()
  {
  int array[MAX];
  for(int i=0;i<MAX;++i)
  array[i]=i+1;
  show(array,MAX);
  srand(time(NULL));
  for(int i=0;i<MAX;++i)
  {
  int start=rand()%MAX;
  int temp=array[i];
  array[i]=array[start];
  array[start]=temp;
  }
  show(array,MAX);
  run(array,MAX-2);
  return 0;
  }

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训