`

一道算法题

阅读更多
package cn.lifx.test;

public class OneToNineTest 
{
	public static void main(String[] args)
	{
		OneToNineTest test = new OneToNineTest();
		
		test.findNum();
	}
	
	public void findNum()
	{
		int num1 = 0;
		int num2 = 0;
		int num3 = 0;
		
		int a1, a2, a3, b1, b2, b3;	// for method 1 used
		
		for(int i=1; i<=3; i++)
		{
			for(int j=1; j<=9; j++)
			{
				for(int k=1; k<=9; k++)
				{
					if(j!=i && k!=j && k!=i)
					{
						num1 = 100 * i + 10 * j + k;
						num2 = num1 * 2;
						num3 = num1 * 3;
						
						//method 1
						a1 = num2/100;
						a2 = (num2/10)%10;
						a3 = num2%10;
						
						b1 = num3/100;
						b2 = (num3/10)%10;
						b3 = num3%10;
						
						if(num3<1000 && Diff(a1, a2, a3) && Diff(b1, b2, b3))
						{
							if(Diff(i, j, k, a1, a2, a3, b1, b2, b3))
							{
								System.out.println("The three numbers are : " + num1 + " " + num2 + " " + num3);
							}
						}
						
						//method 2
//						if(num3<1000 && Diff(num1, num2) && Diff(num1, num3) && Diff(num2, num3))
//						{
//							System.out.println("The three numbers are : " + num1 + " " + num2 + " " + num3);
//						}
					}
				}
			}
		}
	}
	
	//method 1
	public boolean Diff(int a1, int a2, int a3, int b1, int b2, int b3, int c1, int c2, int c3)
	{
		boolean flag = false;
		
		if(Diff(a1, b1, b2, b3) && Diff(a2, b1, b2, b3) && Diff(a3, b1, b2, b3) &&
		   Diff(a1, c1, c2, c3) && Diff(a2, c1, c2, c3) && Diff(a3, c1, c2, c3) &&
		   Diff(b1, c1, c2, c3) && Diff(b2, c1, c2, c3) && Diff(b3, c1, c2, c3))
		{
			flag = true;
		}
		
		return flag;
	}
	
	//method 2
	public boolean Diff(int num1, int num2)
	{
		boolean flag = false;
		
		int a1 = num1/100;
		int a2 = (num1/10)%10;
		int a3 = num1%10;
		
		int b1 = num2/100;
		int b2 = (num2/10)%10;
		int b3 = num2%10;
		
		if(Diff(a1, a2, a3) && Diff(b1, b2, b3) &&
		   Diff(a1, b1, b2, b3) && Diff(a2, b1, b2, b3) && Diff(a3, b1, b2, b3))
		{
			flag = true;
		}
		
		return flag;
	}
	
	//public use
	public boolean Diff(int a, int b, int c)
	{
		boolean flag = false;
		
		if(a!=b && a!=c && b!=c && a!=0 && b!=0 && c!=0)
			flag = true;
		
		return flag;
	}
	
	public boolean Diff(int a, int b, int c, int d)
	{
		boolean flag = false;
		
		if(a != b && a != c && a != d)
			flag = true;
		
		return flag;
	}
}

 

输出为:

 

The three numbers are : 192 384 576
The three numbers are : 219 438 657
The three numbers are : 273 546 819
The three numbers are : 327 654 981

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics