[交流]
【分享】关于9个数字求和的C语言程序 已有9人参与
郁闷,刚发上去就被干掉了。我再发一个贴吧。
经过我一下午加一晚上(大约是下午4点到凌晨2点)的连续思考,终于用C实现了这个题目。程序有点长,没有注释,大家凑合围观一下吧。
不明白的地方大家可以相互交流,切磋。呵呵。CODE: #include
#include
#include
#include
#include
struct node
{
int num;
char op;
int digits;
};
int Calc(struct node* p, int n);
int myAtoi(char* begin, int length);
int Find(struct node* p, int n, int sum);
bool genNumber(struct node* p, int n, int r);
void toNumbers(struct node* p, int n);
void genOperator(struct node* p, int n, int flag);
void Print(struct node* p, int n);
char numbers[]="123456789";
int myAtoi(char* begin, int length)
{
int result=0;
char* r=malloc(length+1);
r=strncpy(r,begin,length);
r[length+1]=0;
result=atoi(r);
free(r);
return result;
}
void toNumbers(struct node* p, int n)
{
char* q=&numbers[0];
for(int i=0;i
{
p[i].num=myAtoi(q,p[i].digits);
q+=p[i].digits;
}
}
int Calc(struct node* p, int n)
{
int sum=0;
sum=p[0].num;
if(p[0].op=='-')
sum=0-sum;
for(int i=1;i
{
switch(p[i].op)
{
case '+':
sum+=p[i].num;
break;
case '-':
sum-=p[i].num;
break;
default:
break;
}
}
return sum;
}
bool genNumber(struct node* p, int n, int r)
{
if(r<0)
{
p[n+2].digits++;
p[n+1].digits=0;
p[n].digits=0;
return false;
}
if(n==0)
{
if(r==0)
return false;
p[n].digits=r;
return true;
}
if(n==1)
{
p[n].digits++;
}
if(p[n].digits==0)
{
p[n].digits=1;
}
genNumber(p, n-1, r-p[n].digits);
}
void genOperator(struct node* p, int n, int flag)
{
for(int i=0;i
{
switch(flag & 1)
{
case 0:
p[i].op='+';
break;
case 1:
p[i].op='-';
break;
}
flag=flag>>1;
}
}
int Find(struct node* p, int n, int sum)
{
int total=0;
int res=0;
memset(p, 0, 9*sizeof(struct node));
while(p[n].digits<9)
{
if(genNumber(p, n, 9)==false)
continue;
toNumbers(p, n);
for(int j=0;j
{
genOperator(p, n, j);
res=Calc(p, n);
if(res==sum)
{
for(int k=0;k
{
printf("%c%d",p[k].op,p[k].num);
}
printf("=%d\n",res);
total++;
}
}
}
return total;
}
int main()
{
int sum;
int total=0;
struct node p[9];
memset(p, 0, 9*sizeof(struct node));
printf("Input the sum: ");
scanf("%d",&sum);
puts("Results:");
for(int i=1;i<10;i++)
total+=Find(p, i, sum);
printf("Total is %d\n", total);
} [ Last edited by nono2009 on 2010-10-30 at 15:19 ]