C语言练习 表达式的递归计算
2014-03-25 22:47
267 查看
在1 2 3 4 5 6 7 8 9 之间的8个空之间填入“+”“-”“ ”三种,使表达式的值为110。比如1 2之间填入的是“ ”,则他们成为12。8个都是“ ”则表达式的值为123456789。
输出所有的情况,使表达式的值为110。
#include <STDIO.H>
#include <string>
#include <stdlib.h>
using namespace std;
int total;
void print(string str)
{
printf("%d:",total++);
int i=0,len=str.length();
while(i<len&&str[i]!='1') i++;
for (;i<len;i++)
{
printf("%c",str[i]);
}
printf("=110\n");
}
string atos(int n)
{
if (n==0)
{
return "0";
}
string str="";
int N=1000000000;
while (n/N==0)
{
N=N/10;
}
while (n>0)
{
str+=char('0'+n/N);
n=n%N;
N=N/10;
}
return str;
}
void function(int cur,int pre,string str,int result)
{
if (result==110&&cur>10)
{
print(str);
}
else if (cur>10)
{
return;
}
else
{
function(cur+1,pre*10+cur,str,result);
function(cur+1,cur,str+"+"+atos(pre),result+pre);
function(cur+1,cur,str+"-"+atos(pre),result-pre);
}
}
int main()
{
function(0,0," ",0);
return 0;
}
输出所有的情况,使表达式的值为110。
#include <STDIO.H>
#include <string>
#include <stdlib.h>
using namespace std;
int total;
void print(string str)
{
printf("%d:",total++);
int i=0,len=str.length();
while(i<len&&str[i]!='1') i++;
for (;i<len;i++)
{
printf("%c",str[i]);
}
printf("=110\n");
}
string atos(int n)
{
if (n==0)
{
return "0";
}
string str="";
int N=1000000000;
while (n/N==0)
{
N=N/10;
}
while (n>0)
{
str+=char('0'+n/N);
n=n%N;
N=N/10;
}
return str;
}
void function(int cur,int pre,string str,int result)
{
if (result==110&&cur>10)
{
print(str);
}
else if (cur>10)
{
return;
}
else
{
function(cur+1,pre*10+cur,str,result);
function(cur+1,cur,str+"+"+atos(pre),result+pre);
function(cur+1,cur,str+"-"+atos(pre),result-pre);
}
}
int main()
{
function(0,0," ",0);
return 0;
}
相关文章推荐
- 表达式,转换和计算,用C语言描述--Part3
- C语言实现括号匹配,中缀表达式转后缀表达式并计算具体代码实现
- 第05天C语言(10):递归练习02
- 【openjudge 计算概论(A)】[函数递归练习(4)]
- 【分治】计算概论(A) / 函数递归练习(1)多边形游戏
- Paradigms of Computer Programming,编程模式学习中递归调用的练习02-计算素数
- 用c语言计算简单的递归问题
- 一个递归计算数学表达式的函数
- C语言表达式计算顺序的一个小问题
- 栈练习之C语言中实现中缀转后缀表达式
- 【openjudge 计算概论(A)】[函数递归练习(3)]
- C语言printf函数输出表达式中的计算顺序
- 一个递归计算数学表达式的函数
- C语言——递归练习
- 递归--练习10--noi1696逆波兰表达式
- c语言递归练习习题
- 算法练习——表达式计算
- C语言实验——计算表达式 (sdut oj)
- ACM递推递归练习F计算组合数
- C语言实现任意长度多项式计算(非递归,不带括号)