题目要求如下:
给你n根火柴棒,你可以拼出多少个形如“A+B=C”的等式?等式中的A、B、C是用火柴棒拼出的整数(若该数非零,则最高位不能是0)。用火柴棒拼数字0--9的拼法如图所示:
注意
- 加号与等号各自需要2根火柴棒
- 如果A≠B,则A+B=C与B+A=C视为不同的等式(A、B、C>=0)
- n根火柴棒必须全部用上
采用枚举的方法,代码如下:
#include <iostream>
using namespace std;
int f[10] = {6,2,5,5,4,5,6,3,7,6};//标记0-9各用多少火柴
int fun(int x) {
int sum = 0;
if (x == 0)
{
return 6;
}
while (x > 0)
{
sum += f[x % 10];//每次加上位数所用火柴
x = x/ 10;
}
return sum;
}
int main () {
/* + = 一共用去4个火柴,总火柴数不超过24,数字1用的火柴最少,是2个
说明用来做等式的火柴最多20个,那么其实每个数不超过1111,枚举即可*/
int num;
cout << "输入火柴棍的数量" << endl;
cin >> num;
int a = 0;//记录能有几个等式
for (int i = 0; i < 1111; i++)
{
for (int j = 0; j < 1111; j++)
{
if (fun(i) + fun(j) + fun(i + j) == num - 4)
{
cout << i << "+" << j << "=" << i+j << endl;
a ++;
}
}
}
cout << "一共能拼" << a <<"个等式" << endl;
getchar();getchar();
}