算法入门刷题(1)


算法入门刷题(1)

习题2-6 排列(permutation)
题目:用1,2,3……,9组成3个三位数abc,def和ghi,每个数字恰好使用一次,要求abc:def:ghi=1:2:3.输出所有解。

我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include<stdio.h>
int main()
{
int abc = 0, def = 0, ghi = 0;
int a=0, b=0, c=0, d=0, e=0, f=0, g=0, h=0, i=0;
int sum = 0;
int flag = 0;//初始化数据以及定义全局变量
for ( abc = 123; abc < 329; abc++)
{
def = 2 * abc;
ghi = 3 * abc;
a = abc / 100;
b = (abc % 100) / 10;
c = abc % 10;
d = def / 100;
e = (def % 100) / 10;
f = def % 10;
g = ghi / 100;
h = (ghi % 100) / 10;
i = ghi % 10;//分离这九位数字
int s[9] = { a,b,c,d,e,f,g,h,i };//将这九位数字存入数组,以通过遍历数组来判断这九个数字的特征
for (int j = 0; j < 9; j++)
{
if (s[j] != 0)
sum++;
}
if (sum == 9)//判断这九位数是不是0,如果都不是0则执行
{
for (int k = 0; k < 8; k++)
for (int m = k + 1; m < 9; m++)
{
if (s[k] == s[m])
flag++;
}
if (flag == 0)//判断九个数中是否有数字相等,如果都不相等则执行
{
printf("%d %d %d\n", abc, def, ghi);
}
}
sum = 0;
flag = 0;//sum标志和flag标志置零,以便下次循环判断
}
return 0;
}

学习代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//方法一:九个数相加和为45,相乘为362880
#include<iostream>
#include<cstdio>
using namespace std;

void result(int num, int &result_add, int &result_mul)
{
int i, j, k;

i = num / 100; //百位
j = num / 10 % 10; //十位
k = num % 10; //个位

result_add += i + j + k; //分解出来的位数相加
result_mul *= i * j * k; //相乘
}

int main()
{
int i, j, k;
int result_add, result_mul;
for(i = 123; i <=329; i++)
{
j = i * 2;
k = i * 3;
result_add = 0;
result_mul = 1;
result(i, result_add, result_mul);
result(j, result_add, result_mul);
result(k, result_add, result_mul);
if(result_add == 45 && result_mul == 362880)
printf("%d %d %d\n", i, j, k);
}
return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//将abcdefghi用字符串存起来,再进行比较,存在一到九就输出abc,def,ghi
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int main(int argc, const char* argv[])
{
int n, i, j;
char a[10];//数组定义比实际大一些
for (n = 123; n < 330; n++)
{
sprintf_s(a, "%d", n * 1000000 + n * 2 * 1000 + n * 3);//将abcdefghi存入到字符串a中
for (j = 0, i = '1'; i <= '9'; memchr(a, i++, 9) && j++);//比较1到9,用j记录
if (j == 9)
{
printf("%d %d %d \n", n, n * 2, n * 3);
}
}
return 0;
}



文章作者: Andy
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Andy !
  目录