记一个函数:sprintf

问题描述

从键盘输入一个数字,输出所有的形如ABC*DE的一个算式,且满足ABCDE里面的所有数字都在我们输入的数字集合中。

在这个算式中,每行数字都属于2357中的一个数字。


Algorithm

如果是在以前,我肯定会这么做:

首先枚举这两个数ABC和DE,然后判断他们算式相乘的两个数以及结果,不断模10来判断是否每一个数字都属于输入的数字。

但是我发现了一个很厉害的函数:sprintf

简单来说,sprintf可以将数字储存到一个字符串里面。

此外,还有另一个函数:strchr

它的作用是检查某一个元素在一个字符串里第一次出现的位置,如果有,返回一个指针,反之返回NULL。

扫描二维码关注公众号,回复: 5153236 查看本文章

现在看完整代码。


AC

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 
 5 using namespace std;
 6 
 7 int fun()
 8 {
 9     char a[11], temp[99];
10     int c = 0;
11     cin>>a;
12     for(int i=100;i<1000;i++){
13         for(int j=10;j<100;j++){
14             sprintf(temp, "%d%d%d%d%d", i, j, (j%10)*i, (j/10)*i, i*j);
15             bool f = true;
16             for(int k=0;k<strlen(temp);k++){
17                 if(strchr(a, temp[k]) == NULL){
18                     f = false;
19                     break;
20                 }
21             }
22             if(f){
23                 printf("<%d>\n", ++c);
24                 printf("%5d\n", i);
25                 printf("X%4d\n", j);
26                 printf("-----\n");
27                 printf("%5d\n", i*(j%10));
28                 printf("%4d\n", i*(j/10));
29                 printf("-----\n");
30                 printf("%5d\n", i*j);
31             }
32         }
33     }
34     if(!c) cout<<"NULL, pleas input next..."<<'\n';
35     return 0;
36  } 
37  
38 int main()
39 {
40     while(1)
41     {
42         fun();
43     }
44     
45     return 0;
46 }
View Code

猜你喜欢

转载自www.cnblogs.com/mabeyTang/p/10356107.html