您的位置:首页 > 其它

算法入门经典习题2-10

2015-08-24 20:58 267 查看
算法入门经典习题2-10,在三位数中找这样的三位数,一共10个不同数字,构成每位数字都不相同的三位数。令其为a,b,c.使的a:b:c =1:2:3

我的方法:暴力求解法

写了三个函数,
istrue()  ----->判断一个三位数各位是否相同,不相同返回1
istrue1()------>判断一个数与一个三位数的各位是否相同,不相同返回1
istrue2()------>判断两个三位数各位是否相同,不相同返回1


然后就是对 倍数为1的那个三位数进行穷举,

for(i=102,i<329;i++) //原因数学上可以证明

temp1 = 2*i;temp2=3*i;

这样temp1,temp2就保存了题干中b,c的值,然后利用前面写的函数判断他们三个是否每位都不同即可

附上源代码:

#include <iostream>
#define A  1
using namespace std;
int istrue(int num){     //函数
int a,b,c;
a = num/100;
c =num%10;
b = (num%100)/10;
if(a!=b &&a!=c &&b!=c) return 1;
return 0;
}
int istrue1(int k,int num){   //函数
int a,b,c;
a = num/100;
c =num%10;
b = (num%100)/10;
if(k!=a &&k!=b&& k!=c) return 1;
return 0;
}
int istrue2(int num1,int num2){   //函数
int a,b,c;
a = num1/100;
c =num1%10;
b = (num1%100)/10;
if(istrue1(a,num2)==1 && istrue1(b,num2)==1 &&istrue1(c,num2)==1) return 1;
return 0;
}
void main()
{
#if  A
int temp1,temp2,flag=0;
for(int i=102;i<=329;i++){     //穷举模块
temp1 =  2*i;
temp2 =  3*i;
if(istrue(temp1)==1 && istrue(temp2)==1){  //判断temp1,temp2各位都不一样
if(istrue2(temp1,temp2)==1 && istrue2(temp1,i)==1 && istrue2(temp2,i)==1)
cout<<i<<" "<<temp1<<" "<<temp2<<endl;
flag =1;
}
}
if(flag) return;
cout<<"not find"<<endl;
#endif
}


附上运行结果:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: