C++编程解析-P1149火柴棒等式-函数

题目1
题目2
题目3
解题思路:
首先,我们要将数字0-9所用的火柴棒数目存储到数组中,因为,n的范围小于等于24,所以,999是等式当中可能出现的最大的数字,所以,我们从0-999,挑选两个加数,计算出两个加数所用的火柴数目,再计算出两个加数和的火柴数目,将前两项火柴数目的和加上加号和等号所用的火柴数目。是否将火柴全部用完。用完则满足条件,否则,则不是。

参考程序:

#include<iostream>
using namespace std;
const int equ = 4;
const int MAX_NUM = 999;      //"+","="用去的火柴数 
int num[10] = {6,2,5,5,4,5,6,3,7,6};   //数字对应的火柴数目
//数字n用的火柴数 
int matchNum(int n){
	if(n == 0)
		return num[0];
	int total = 0;
	while(n){
		total += num[n%10];
		n /= 10;
	}
	return total;
} 
//等式成立判断 
bool equSuccess(int plus1,int plus2,int n){
	if((matchNum(plus1) + matchNum(plus2) + matchNum(plus1+plus2))== n)
		return true;
	return false;
}
int main(){
	int n;
	int res = 0;
	cin>>n;
	n -= equ;
	//查找所有可能性 
	for(int i = 0;i < MAX_NUM;i++){
		for(int j = 0;j < MAX_NUM;j++){
			if(equSuccess(i,j,n)){
				res++;
			}
		}
	}
	cout<<res;
	return 0;
}

程序结果:
程序结果1
程序结果2
问候

发布了34 篇原创文章 · 获赞 4 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/xingzhe_666/article/details/102545506