A vampire number is a number with an even number of digits, which can be multiplied by a pair of numbers, which contains the number of half-digits of the product, where the number selected from the original number can be arbitrarily sorted. Numbers ending with two 0 are not allowed.
Write a program to find all the vampire numbers in a 4-digit number.
is actually a simple DFS. We can extract the original numbers and then fill in the new two numbers. If the product of two new numbers happens to be the original number, then this number is a vampire number. The Isvampire class in the following code provides the ability to determine whether a number is a vampire number, If yes, return one of the new numbers, otherwise return-1;
The code is as follows:
package lkl; Public class Main {public static void main (string[] args) {Isvampire im = new isvampire (); for (int i=1000 ; I<= 9999 ; i++) {int t=im.check (i); if (T!=-1 ) {System. out . println (I+ +i+ "=" +t+ "*" +i/t); } } }}
Package Lkl;import java.util.*; Public classIsvampire {Private intNum,x;Private int[] A=New int[4];Private int[] vis=New int[4]; Public void DFS(intCurintT1,intT2) {if(num!=-1)return;if(cur==4){if(t1*t2==x) {num=t1; }return; } for(intI=0;i<4; i++) {if(cur==0&&a[i]==0)Continue;if(cur==2&&a[i]==0)Continue;if(vis[i]==1)Continue; vis[i]=1;if(cur<=1) DFS (cur+1, t1*Ten+A[I],T2);if(cur>=2) DFS (cur+1, t1,t2*Ten+a[i]); vis[i]=0;if(num!=-1)return; } } Public void Init(intx) {num=-1; This. x=x;/// Java does not have the Memsest function in C + +, you can call the Fill function in arrays /// Uniform padding initial value, but because Java cannot manipulate memory directly, this method is actually /// heap arrays are populated individuallyArrays.fill (A,0); for(intI=0;i<4; i++) {a[i]=x%Ten; X/=Ten; } } Public int Check(intXX) {Init (XX); Dfs0,0,0);returnNum }}
Thinking in java--vampire numbers