转载自 http://yangl.iteye.com/blog/264634
这个算法应该是比较简单的了。算法中用到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.*;
- publicclass Vampire extends Applet {
- privateint num1, num2, product;
- privateint[] startDigit = newint[4];
- privateint[] productDigit = newint[4];
- privateint count = 0;
- privateint vampCount = 0;
- privateint x, y;
- publicvoid 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;
- }
- }
- }
- }
- }
- }
- } ///:~