金山笔试题,2007-6-3

出自求职百科

跳转到: 导航, 搜索

任一给4个正整数,求出它的所有加和的总数。并按相应的格式打印出来

如:1,2,3,4

共有加和数10种。

结果打印如下:

和为1有1种

1=1;

和为2有1种

2=2;

...

和为6有2种

6=1+2+3;

6=2+4;

...

和为10有1种

10=1+2+3+4;

(1)

int Num[4]; /* 输入的四个数 */

int Resoult[15]; /* C(1,4) + C(2,4) + C(3,4) + C(4,4)最多15种组合结果*/

int total=0; /* 一共有几种结果 */

void Input(); /* 输入 */

void End(); /* 结束 */

void PrintNum();

void SortNum

();

对输入的四个数排序 */

void Stat(int point,int sum,int curr_count,int count); /* 统计一共有几种组合结果 */

/* 显示每种结果的组合情况 */

void combin(int point,int sum,int target,int array[],int pot);

main()

{int count,point,array[4];

Input();

SortNum();

for(count=1;count<=4;count++) /* 递归寻找所有组合结果 */

for(point=0;point<=4-count;point++)

Stat(point,0,0,count);

for(count=0;count<total;count++) { /* 显示结果 */

printf("way of %d\n",Resoult[count]);

for(point=0;point<=3;point++)

combin(point,0,Resoult[count],array,0);

}

End();

}

void combin(int point,int sum,int target,int array[],int pot)

{int i;

if(point==4)

return;

sum=sum+Num[point];

array[pot]=Num[point];

pot++;

if(sum>target)

return;

else if(sum==target) { /*显示结果*/

for(i=0;i<pot;i++)

printf("%d ",array[i]);

printf("\n";

}

else

for(i=point+1;i<4;i++)

combin(i,sum,target,array,pot);

}

void Stat(int point,int sum,int curr_count,int count)

{int i;

if(point==4)

return;

sum=sum+Num[point];

curr_count++;

if(curr_count  != count) { /* 继续递归累加 */

for(i = point+1  ;i < 4; i++)

Stat(i,sum,curr_count,count);

}

else { /* 判断是否添加新的可能结果 */

if(total==0) {

Resoult[total]=sum;

total++;

}

else {

for(i=0;i<total;i++)

if(Resoult[i]==sum)

break;

if(i>=total) {

Resoult[total]=sum;

total++;

}

}

}

}

void Input()

{

int i;

for(i = 0;i < 4;i++)

scanf("%d" , &Num[i]);

}

void SortNum()

{

int i,j,t;

for(i = 0;i < 3;i++)

for(j = i+1;j < 4;j++)

if(Num[j] < Num[i]) {

t = Num[i];

Num[i] = Num[j];

Num[j] = t;

}

}

void End()

{

getch();

}

(2)

  1. include <stdio.h>
  1. define ARRAY_SIZE 4
  1. define MAX_NUM (1<<ARRAY_SIZE)

int main(void)

{

int h,i, j;

int sum;

int a[ARRAY_SIZE] = {1,2,3,4};

int count = 0;

for(h=1;h<=10;h++)

{

for(i = 0; i < MAX_NUM; i++)

{

sum = 0;

for(j = 0; j < ARRAY_SIZE; j++)

{

if(i & (1 << j))

sum += a[j];

}


if(h == sum)

{

printf("%d: ", ++count);

for(j = 0; j < ARRAY_SIZE; j++)

{

if(i & (1 << j))

printf("%d + ", a[j]);

}

printf("\b\b= %d.\n",h);

}

}

}

printf("\nTotal: %d.\n", count);

return 0;

}


个人工具
公司索引
  • A   B   C   D   E   F   G
  • H   I   J   K   L   M   N
  • O    P
  •     Q    R    S    T
  • U    V    W    X    Y    Z
工具箱