警匪110

 问题描述:

匪警请拨110,即使手机欠费也可拨通!

   为了保障社会秩序,保护人民群众生命财产安全,警察叔叔需要与罪犯斗智斗勇,因而需要经常性地进行体力训练和智力训练!

   某批警察叔叔正在进行智力训练:

    12 3 4 5 6 7 8 9 =110;

    请看上边的算式,为了使等式成立,需要在数字间填入加号或者减号(可以不填,但不能填入其它符号)。之间没有填入符号的数字组合成一个数,例如:12+34+56+7-8+9 就是一种合格的填法;123+4+5+67-89 是另一个可能的答案。

   请你利用计算机的优势,帮助警察叔叔快速找到所有答案。

   每个答案占一行。形如:

12+34+56+7-8+9

123+4+5+67-89

...... 


#include<stdio.h>
#include<math.h>
#define n 8

int a[9]={1,2,3,4,5,6,7,8,9};
int main()
{
	int sum;
	int ans=110;
	int i,j,k,x,y;
	int num,temp;
	int cnt=0;
	int count1,count2,count3;
	for(num=0;num<pow(3,n);num++)
	{
		temp=num;
		sum=0;
		int flag=1;
		count1=a[0]; 
		for(j=1;j<=n;j++)
		{
			
			if(temp%3==0)    //两个数字之间没有操作符 
			{
				count1=count1*10+a[j];					
			}
			if(temp%3==1)    //两个数字之间的操作符为‘+’ 
			{
				if(flag==1)      //上一个操作符为‘+’ 
				{
					sum+=count1;
					count1=a[j];	
				}
				if(flag==2)     //上一个操作符为‘-’ 
				{
					sum-=count1;
					count1=a[j];
				}
				flag=1;
			}
			
			if(temp%3==2)    //两个数字之间的操作符为‘-’ 
			{
				if(flag==1)      //上一个操作符为‘+’ 
				{
					sum+=count1;
					count1=a[j];
				}
				
				if(flag==2)     //上一个操作符为‘-’ 
				{
					sum-=count1;
					count1=a[j];
				}
				flag=2;
			}	
				
			temp/=3;	
		}
		if(flag==1)
			sum+=count1;
		if(flag==2)
			sum-=count1; 
			
		if(sum==ans)
		{
			cnt++;
			temp=num;
			for(i=0;i<n;i++)
			{
				if(temp%3==0)
				{
					printf("%d",a[i]);
				}
				if(temp%3==1)
					printf("%d+",a[i]);
				if(temp%3==2)
					printf("%d-",a[i]);
					temp/=3;
			}
			printf("%d\n",a[n]);
			
		}
	}
	printf("%d\n",cnt);
	return 0;
 } 
 


也可以不用数组,用j把数组a换掉

for(num=0;num<pow(3,n);num++)
	{
		temp=num;
		sum=0;
		int flag=1;
		count1=1; 
		for(j=1;j<=n;j++)
		{
			k=j+1;
			if(temp%3==0)    //两个数字之间没有操作符 
			{
				count1=count1*10+k;					
			}
			if(temp%3==1)    //两个数字之间的操作符为‘+’ 
			{
				if(flag==1)      //上一个操作符为‘+’ 
				{
					sum+=count1;
					count1=k;	
				}
				if(flag==2)     //上一个操作符为‘-’ 
				{
					sum-=count1;
					count1=k;
				}
				flag=1;
			}
			
			if(temp%3==2)    //两个数字之间的操作符为‘-’ 
			{
				if(flag==1)      //上一个操作符为‘+’ 
				{
					sum+=count1;
					count1=k;
				}
				
				if(flag==2)     //上一个操作符为‘-’ 
				{
					sum-=count1;
					count1=k;
				}
				flag=2;
			}	
				
			temp/=3;	
		}
		if(flag==1)
			sum+=count1;
		if(flag==2)
			sum-=count1; 
			
		if(sum==ans)
		{
		//	printf("$$$$$$$$$$\n");
			cnt++;
			temp=num;
			for(i=1;i<=n;i++)
			{
				if(temp%3==0)
				{
					printf("%d",i);
				}
				if(temp%3==1)
					printf("%d+",i);
				if(temp%3==2)
					printf("%d-",i);
					temp/=3;
			}
			printf("9\n");
			
		}
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值