/********************************************
* 输入一个正整数X,在下面的等式左边的数字之间添加+号或者-号,使得等式成立。
* 1 2 3 4 5 6 7 8 9 = X
* 比如: <span style="font-family: Arial, Helvetica, sans-serif;">12-34+5-67+89 = 5 </span>1+23+4-5+6-7-8-9 = 5
请编写程序,统计满足输入整数的所有整数个数。
输入: 正整数,等式右边的数字
输出: 使该等式成立的个数
样例输入:5
样例输出:21
* 变形==》可以在最前面的数字之前添加-号;<span style="font-family: Arial, Helvetica, sans-serif;"> </span>
<pre name="code" class="cpp"> 样例输入:5
样例输出:40
88888888888888888888888888888888888888888888
解题思路:将其等价于一串字符串,即在数字之间任意插入+号或-号,形成一串字符串;然后解析该字符串,计算最终结果,判断是否等于X;
利用了递归思想。
88888888888888888888888888888888888888888888
********************************************/
#include<iostream>
using namespace std;
int GetCount(int a[],int pos,int n,char str[],int current_pos,int x);
int GetValue(char str[],int len);
int main()
{
int a[]={1,2,3,4,5,6,7,8,9};
int x=5,pos=0,current_pos=0,n=9;
char str[21];
int count=GetCount(a,pos,n,str,current_pos,x);
cout<<count<<endl;
return 0;
}
int GetCount(int a[],int pos,int n,char str[],int current_pos,int x)
{
int count=0;
if(pos==n)
{
int value=GetValue(str,current_pos);
if(value==x)
{
for(int k=0;k<=current_pos-1;k++)
cout<<str[k];
cout<<"= "<<value<<endl;
return 1;
}
else return 0;
}
if(pos<n)
{
if(pos==0)
{
str[current_pos]='-';
str[current_pos+1]=a[pos]+'0';
count+=GetCount(a,pos+1,n,str,current_pos+2,x);
str[current_pos]=a[pos]+'0';
count+=GetCount(a,pos+1,n,str,current_pos+1,x);
}
if(pos>0)
{
//str[current_pos]='-';
//str[current_pos+1]=a[pos]+'0';
//count+=GetCount(a,pos+1,n,str,current_pos+2,x);
str[current_pos]='+';
str[current_pos+1]=a[pos]+'0';
count+=GetCount(a,pos+1,n,str,current_pos+2,x);
str[current_pos]=' ';
str[current_pos+1]=a[pos]+'0';
count+=GetCount(a,pos+1,n,str,current_pos+2,x);
}
}
return count;
}
int GetValue(char str[],int len)
{
int i=0,count=0;
int value=0;
int num[9];
int flag=-1;
while(i<len)
{
switch(str[i])
{
case '+':
{
if(flag==-1 && count>0)flag=0;
int temp_value=0;
for(int k=0;k<count-1;k++)
{
temp_value=(temp_value+num[k])*10;
}
if(count>0)temp_value+=num[count-1];
if(flag==0)
{
value+=temp_value;
}
if(flag==1)
{
value-=temp_value;
}
flag=0;
count=0;
break;
}
case '-':
{
if(flag==-1&&count==0)flag=1;
else if(flag==-1 && count>0)flag=0;
int temp_value=0;
for(int k=0;k<count-1;k++)
{
temp_value=(temp_value+num[k])*10;
}
if(count>0)temp_value+=num[count-1];
if(flag==0)
{
value+=temp_value;
}
if(flag==1)
{
value-=temp_value;
}
flag=1;
count=0;
break;
}
case ' ':
{
break;
}
default :
{
num[count]=str[i]-'0';
count++;
break;
}
}
i++;
}
if(count>0)
{
int temp_value2=0;
for(int k=0;k<count-1;k++)
{
temp_value2=(temp_value2+num[k])*10;
}
temp_value2+=num[count-1];
if(flag==-1 || flag==0)
{
value+=temp_value2;
}
if(flag==1) value-=temp_value2;
}
return value;
}