华为一道面试题及其解决方法

来源:互联网 发布:安装mac os x不能验证 编辑:程序博客网 时间:2024/04/28 16:00

那天在CSDN上看到华为一道面试题(不知真假),有好多人发表了个人意见。回去好好考虑了一下,现在把个人考虑的结果发布如下,愿与大家共同讨论,有错误的地方还请多多指正。

题目:(华为面试)N个人站一圈,某个人从1开始报数,报偶数的淘汰出局,如此循环下
     去,问最后剩下的是第几个人?
要求:数学计算(不能编程)
*************************************************************************
寻找规律:
标号i  共有N(i)个人  最后剩下第M(i)个人
1         1                       1
2         2                       1
3         3                       3
4         4                       1
5         5                       3
6         6                       5
7         7                       7
8         8                       1
9         9                       3
10       10                     5
11       11                     7
12       12                     9
13       13                     11
14       14                     13
15       15                     15
16       16                     1
17       17                     3
18       18                     5
19       19                     7
20       20                     9
21       21                     11
22       22                     13
23       23                     15
24       24                     17
25       25                     19
26       26                     21
27       27                     23
28       28                     25
29       29                     27
30       30                     29
31       31                     31
...          ...                      ...
规律总结:
(1)N(i)=i,i>=1
(2)当N(i)=1或者(M(i-1)=N(i-1)且i>1)时,M(i)=1
(3)当(M(i-1)!=N(i-1)且i>1)时,M(i)=M(i-1)+2
以上规律可以用数学归纳法加以证明。
利用上面这种方法编写出来的程序可以使用递归简化编程,但会增加运行时间和占用更多的存储空间,

C语言源代码如下:
/*Date:12/03/2005*/
/*Author:FreeBird Sky*/
/*QQ:86008628*/
/*Email:gramming@126.com*/
int m(int n)
{
 if(n==1||m(n-1)==n-1)
  return 1;
 else
  return m(n-1)+2;
}
main()
{
 int n;
 printf("Please input the value of n:");
 scanf("%d",&n);
 printf("The remain one is:%d/n",m(n));
}
下面给出一种使用循环单链表进行判断的更有效的方法,但是没有利用上面的数学规律,

而是完全模拟事件的全过程,从而得出结果,C语言源代码如下:
/*Date:12/03/2005*/
/*Author:FreeBird Sky*/
/*QQ:86008628*/
/*Email:gramming@126.com*/
struct Node
{
 int num;
 int lable;
 struct Node *next;
};
main()
{
 struct Node *phead,*ptail,*p,*q;
 int i,n,m;
 m=0;
 printf("Please input the value of n:");
 scanf("%d",&n);
 phead=(struct Node*)malloc(sizeof(struct Node));
 phead->num=1;
 phead->next=phead;
 p=phead;
 for(i=2;i<=n;i++)
 {
  ptail=(struct Node*)malloc(sizeof(struct Node));
  ptail->num=i;
  ptail->next=phead;
  p->next=ptail;
  p=p->next;
 }
 while(n!=1)
 {
  m++;
  p->next->lable=m;
  if(p->next->lable%2==0)
  {
   q=phead;
   do{
      printf("%4d",q->num);
      q=q->next;
     }while(q!=phead);
   printf("/n");
   if(p->next==phead)
     phead=p->next->next;
   if(p->next==ptail)
     ptail=p;
   p->next=p->next->next;
   n--;
  }
  else
  p=p->next;
 }
 printf("%4d/n",p->num);
 printf("The remain one is:%d/n",p->num);
}

/*以上两个程序均在TC2.0环境下编译运行成功*/

原创粉丝点击