思路:A+B=C 假设A数要a根火柴棒,B数要b根火柴棒,C数要c根火柴棒
所以 a 2 b 2 c 要输入n根火柴,所以要满足a+b+c+4 == n
只需要枚举出a 枚举出b 就相当于枚举出c了
然后使用火柴棒最少的数字是1,用使用最少的数字能够拼出位数多的数,尝试1111+1=1112 一共花费21根火柴棒,n最大24,除去+和=还剩20根,也就是说无法拼出4位数的1111。
其次用花费火柴棒第二少的数字7,711+1=712 一共花费19根
为了防止没有考虑齐全,直接计算1000以内就行(枚举)
重要!!!数除,A和B分别获取数字每一位数对应的火柴棒数
话不多说,直接上代码!!!
package lanqiao;
import java.util.Scanner;
public class 枚举Test {
static int[] num = new int[]{6,2,5,5,4,5,6,3,7,6};
public static void main(String[] args) {
//火柴棒等式 24根火柴棒 拼A+B=C的等式 +=占4根火柴棒 A B C>=0
//问可以拼多少个这样的等式
//如题 0 1 2 3 4 5 6 7 8 9
//所需火柴棒数 6 2 5 5 4 5 6 3 7 6
Scanner sc = new Scanner(System.in);
int n = sc.nextInt()-4;//接收输入的n根火柴
int count = 0;
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
int a = getNum(i);
int b = getNum(j);
int cNum = i + j;
int c = getNum(cNum);
if (a+b+c==n){
count++;
// System.out.print("a="+a+" b="+b+" c="+c+" ");
// System.out.println(i+"+"+j+"="+cNum);
}
}
}
System.out.println(count);
}
//获取对应数字的所需火柴棒数
public static int getNum(int i){
int sumNum = 0;
if (i == 0){
return 6;
}
while (i != 0){
int now = i % 10;
sumNum += num[now];
i/=10;
}
return sumNum;
}
}
简单易懂的暴力是真好用,适合初学者!(因为我也菜鸟哈哈哈哈!适当骗分用!)
但是暴力枚举容易超时,需要注意的是运算量最好不要超过1e7
本题写出来的运行时间是981ms,只能说是一种不用太动脑子的解法!
还有一个优化版本!
先枚举0-2000的每个数需要多少根火柴棒(其实由上面可以推出,枚举1000左右就行了),存入数组,然后再进行枚举A+B=C满足情况的时候进行累加。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
int count = 0;
int c[] = new int[2001];
c[0] = 6;
//a存储0-9每个数字所用的火柴数目
int a[] = new int [] {
6,2,5,5,4,5,6,3,7,6
};
for(int i=1;i<=2000;i++) {
int j=i;
while(j>=1)//求每个数所用的火柴棒
{
c[i] += a[j%10];
j=j/10;
}
}
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 1000; j++) {
if(c[i]+c[j]+c[i+j]+4==input) {
count++;
}
}
}
System.out.println(count);
scanner.close();
}
}
优化过后的版本比上面的运行时间大概快了20%!!!!