Thinking in java--vampire numbers

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.