1 2 3 4 5 6 7 8 9 = 81 在1-9之间添加加减乘除号,使等式成立

时间:2022-11-05 15:35:40
  1 /************************************************************************/
2 /* 1 2 3 4 5 6 7 8 9 = 81 在1-9之间添加加减乘除号,使等式成立。 */
3 /************************************************************************/
4 #include <iostream>
5 using namespace std;
6
7 bool stop = false; //控制遍历终止
8 int count_ = 0; //计算结果数量
9 int count_loop = 0; //计算循环次数
10
11 void trans(int* arr, int index) //从右往左递增遍历
12 {
13 if(index < 0)
14 return;
15 int temp = arr[index] / 4;
16 if(temp <= 0) //判断是否需要进位
17 return;
18 arr[index] = arr[index] % 4;
19 if(index == 0) //判断是否已经遍历完
20 {
21 stop = true;
22 return;
23 }
24 arr[index - 1] += temp;
25 trans(arr, index - 1);
26 }
27
28 void show(int* symbol, int len) //处理每次遍历结果,并显示正确项
29 {
30 float number[9]= {1,2,3,4,5,6,7,8,9};
31 int symbol_copy[9];
32 for(int i = 0; i < 9; ++i)
33 {
34 symbol_copy[i] = symbol[i];
35 }
36 /*
37 计算出带乘除号的结果,将前面的项置为0,符号沿用前面的符号
38 */
39 for(int i = 0; i < len -1; i++) //合并乘除项
40 {
41 if(symbol_copy[i] == 2 || symbol_copy[i] == 3)
42 {
43 if(symbol_copy[i] == 2) //计算合并后的结果
44 {
45 number[i+1] = number[i] * number[i+1];
46 }
47 else if(symbol_copy[i] == 3)
48 {
49 number[i+1] = number[i] / number[i+1];
50 }
51 number[i] = 0;//合并后将前一个数置零
52
53 if(i == 0)
54 symbol_copy[i] = 0;
55 else
56 symbol_copy[i] = symbol_copy[i-1]; //乘除结果合并,符号替换成前面的符号
57 }
58 }
59
60 float num = number[0];
61 for(int i = 0; i < len - 1; ++i) //计算结果
62 {
63 if(symbol_copy[i] == 0)
64 num += number[i+1];
65 else if(symbol_copy[i] == 1)
66 num -= number[i+1];
67 }
68
69 if(num == 81)//打印正确等式
70 {
71 count_++;
72 for(int i = 0; i < len -1; ++i)
73 {
74 cout<<i+1;
75 if(symbol[i] == 0)
76 cout<<"+";
77 else if(symbol[i] == 1)
78 cout<<"-";
79 else if(symbol[i] == 2)
80 cout<<"*";
81 else if(symbol[i] == 3)
82 cout<<"/";
83 }
84 cout<<"9=81"<<endl;
85 }
86 }
87
88
89 int main()
90 {
91 int symbol[9] = {0};// [0:+ 1:- 2:* 3:/]
92 int len = 9;
93 while(!stop)
94 {
95 show(symbol, len);
96 symbol[len-2]++;
97 trans(symbol, len-2);
98 count_loop++;
99 }
100 cout<<""<<count_<<" 种可能"<<endl;
101 cout<<"遍历了"<<count_loop<<""<<endl;
102 system("pause");
103 return 0;
104 }

1 2 3 4 5 6 7 8 9 = 81 在1-9之间添加加减乘除号,使等式成立