一道看似有点简单的题,不知道算法怎么写?哪位大虾帮帮忙?
Write a Java program that will find all the possible “vampire numbers.” A vampire number is defined as a four digit numbers in which the two numbers multiplied are in the product, for example, 15 x 93 = 1395. The program should produce no duplicates, and be less than 50-60 lines of code.
------解决方案--------------------
int num = 1000;
for(int i = num; i <= 9999; i++){
String aa = new Integer(num).toString();
String aa0 = aa.subString(0,1);
String aa1 = aa.subString(1,1);
String aa2 = aa.subString(2,1);
String aa3 = aa.subString(3,1);
if(aa0 * aa1 == num){
}
if(aa0* aa2 == num)
if(aa0* aa3 == num)
if(aa1*aa2){
if(aa1*aa3)
if(aa2*aa3)
}
应该可以实现。。。。
不知道有没有更好的方安, 或许这种数字是有其他的规律。。。
------解决方案--------------------
public class VampireNumber
{
private int isVampire(int a, int b)
{
int[] number = new int[4];
number[0] = a / 10;
number[1] = a % 10;
number[2] = b / 10;
number[3] = b % 10;
int c = a * b;
int[] number1 = new int[4];
for (int i = 0, temp = c, div = 1000; i < number1.length; i++, div /= 10)
{
number1[i] = temp / div;
temp = temp % div;
}
if (compare(number, number1))
return c;
else
return -1;
}
private boolean compare(int[] number, int[] number1)
{
number = sort(number);
number1 = sort(number1);
for (int i = 0; i < number.length; i++)
if (number[i] != number1[i])
return false;
return true;
}
private int[] sort(int[] number)
{
for (int i = 0; i < number.length - 1; i++)
for (int j = i; j < number.length-1; j++)
{
if (number[j] > number[j+1])
{
int temp = number[j];
number[j] = number[j+1];
number[j+1] = temp;
}
}
return number;
}
public static void main(String[] args)
{
VampireNumber v = new VampireNumber();
for (int a = 10; a < 100; a++)
{
for (int b = a; b < 100; b++)
{
int c = v.isVampire(a, b);
if (c > 0)
System.out.println( "a = " + a + ", b= " + b + ", c = " + c);
}
}
}
}