吸血鬼数字java_吸血鬼数字

所谓“吸血鬼数字”就是指位数为偶数的数字(我们算得是4位的),可以由一对数字相乘而得到,而这对数字各包含乘积的一半位数字,其中从偶数位数字中选取的数字可以任意排列。以两个0截尾的数字是不允许的。例如:1260=21*60          1827=21*87          2187=27*81

今天在Thinking in JAVA 中做到的练习题。我先自己写了一个算法,但是总感觉太复杂。后来在网上找到一个比较好的算法。如下:

class Eg0410_Vampire{

public static void main(String[] args){

String[] ar_str1,ar_str2;

int sum=0;

for(int i=10;i<100;i++){

for(int j=i+1;j<100;j++){

int i_val=i*j;

if(i_val<1000||i_val>9999) continue; //积小于1000或大于9999排除,继续下一轮环

ar_str1=String.valueOf(i_val).split("");

ar_str2=(String.valueOf(i)+String.valueOf(j)).split("");

java.util.Arrays.sort(ar_str1);

java.util.Arrays.sort(ar_str2);

if(java.util.Arrays.equals(ar_str1, ar_str2)){

//排序后比较,为真则找到一组

sum++;

System.out.println("第"+sum+"组: "+i+"*"+j+"="+i_val);

}

}

}

System.out.println("共找到"+sum+"组吸血鬼数");

}

}

这个算法应该是比较简单的了。算法中用到String.valueOf(j)).split("");的方法来把数字转换为字符串,以拆分数字的方法用的很巧妙了。把数字的比较,转换为对字符串的比较,实在高明。

下面是我在《Thinking in Java, 2nd edition, Annotated Solution Guide Revision 1.0》中找到的答案,也就是Thinking in JAVA的官方答案书上的答案。不过个人感觉没有上面的算法好。

//: c03:E11_Vampire.java

// Solution by Dan Forhan

import java.applet.*;

import java.awt.*;

public class Vampire extends Applet {

private int num1, num2, product;

private int[] startDigit = new int[4];

private int[] productDigit = new int[4];

private int count = 0;

private int vampCount = 0;

private int x, y;

public void paint(Graphics g) {

g.drawString("Vampire Numbers", 10, 20);

g.drawLine(10, 22, 150, 22);

// Positioning for output to applet:

int column = 10, row = 35;

for(num1 = 10; num1 <= 99; num1++)

for(num2 = 10; num2 <= 99; num2++) {

product = num1 * num2;

startDigit[0] = num1 / 10;

startDigit[1] = num1 % 10;

startDigit[2] = num2 / 10;

startDigit[3] = num2 % 10;

productDigit[0] = product / 1000;

productDigit[1] = (product % 1000) / 100;

productDigit[2] = product % 1000 % 100/10;

productDigit[3] = product % 1000 % 100%10;

count = 0;

for(x = 0; x < 4; x++)

for(y = 0; y < 4; y++) {

if (productDigit[x] == startDigit[y]){

count++;

productDigit[x] = -1;

startDigit[y] = -2;

if (count == 4) {

vampCount++;

int a = (int)Math.random() * 100;

int b = (int)Math.random() * 100;

int c = (int)Math.random() * 100;

if (vampCount < 10) {

g.drawString("Vampire number     "

+ vampCount + " is " + num1 +

" * " + num2 + " = "+ product,

column, row);

row += 20;

} else {

g.drawString("Vampire number    "

+ vampCount + " is " + num1 +

" * " + num2 + " = "+ product,

column, row);

row += 20;

}

}

}

}

}

}

} ///:~

最后修改于 2015-06-06 13:10

阅读(?)评论(0)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值