|
C语言趣味程序百例精解之java实现(60)组成三个数 :
题目:
由1到9这九个数字组成三个3位数,要求成1:2:3的比例,数字不重复。
解法一:
**
* 60.分成三个数
*/
public class Test60{
public static void main(String args[]){
new Test60().devideIntoThree60();
}
public void devideIntoThree60() {
int count = 0;
int n1, n2, n3;
for (int a = 1; a <= 9; a++)
for (int b = 1; b <= 9; b++)
for (int c = 1; c <= 9; c++)
for (int d = 1; d <= 9; d++)
for (int e = 1; e <= 9; e++)
for (int f = 1; f <= 9; f++)
for (int g = 1; g <= 9; g++)
for (int h = 1; h <= 9; h++)
for (int i = 1; i <= 9; i++)
if (a + b + c + d + e + f + g + h
+ i == 45
&& notEquls(new int[] { a,
b, c, d, e, f, g,
h, i })) {
n1 = a * 100 + b * 10 + c;
n2 = d * 100 + e * 10 + f;
n3 = g * 100 + h * 10 + i;
if (2 * n1 == n2
&& 3 * n1 == n3) {
count++;
System.out.print(" a=" + a);
System.out.print(" b=" + b);
System.out.print(" c=" + c);
System.out.print(" d=" + d);
System.out.print(" e=" + e);
System.out.print(" f=" + f);
System.out.print(" g=" + g);
System.out.print(" h=" + h);
System.out.println(" i="
+ i);
System.out.println("n1="
+ n1 + " n2=" + n2
+ " n3=" + n3);
}
}
System.out.println("count=" + count);
}
/**
* 判断是否两两不相等
*/
public boolean notEquls(int[] a) {
if (a == null || a.length == 0 || a.length == 1)
return true;
for (int i = 0; i < a.length; i++) {
for (int j = i; j < a.length; j++) {
if (a == a[j] && i != j) {
// System.out.println("a[" + i + "]" + a + " a[" + j +
// "]"
// + a[j] + "---");
return false;
}
}
}
return true;
}
}
C:\bat>java Test60
a=1 b=9 c=2 d=3 e=8 f=4 g=5 h=7 i=6
n1=192 n2=384 n3=576
a=2 b=1 c=9 d=4 e=3 f=8 g=6 h=5 i=7
n1=219 n2=438 n3=657
a=2 b=7 c=3 d=5 e=4 f=6 g=8 h=1 i=9
n1=273 n2=546 n3=819
a=3 b=2 c=7 d=6 e=5 f=4 g=9 h=8 i=1
n1=327 n2=654 n3=981
count=4
解法二
public class Test601{
public static void main(String args[]){
new Test601().OneTwoThree();
}
public void OneTwoThree(){
int count=0;
for(int m=123;m<=333;m++){
if(ok(m,2*m,3*m)){
System.out.printf("No%d:%d %d %d\n",++count,m,2*m,3*m);
}
}
}
public boolean ok(int a,int b,int c){
int x[]=f(a);
int y[]=f(b);
int z[]=f(c);
int w[]={x[0],x[1],x[2],y[0],y[1],y[2],z[0],z[1],z[2]};
return notEquls(w);
}
public int[] f(int n){//求n的各位数字。
int i=0;
int a[]=new int[3];
while(n!=0){
a[i++]=n%10;
n=n/10;
}
return a;
}
/**
* 判断是否两两不相等或有0
*/
public boolean notEquls(int[] a) {
if (a == null || a.length == 0 || a.length == 1)
return true;
for (int i = 0; i < a.length; i++) {
if(a==0) return false;
for (int j = i; j < a.length; j++) {
if (a == a[j] && i != j) {
return false;
}
}
}
return true;
}
}
运行结果:
C:\java>java Test601
No1:192 384 576
No2:219 438 657
No3:273 546 819
No4:327 654 981 |
|