Colorful Number

Problem

A number can be broken into different sub-sequence parts. Suppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245. And this number is a colorful number, since product of every digit of a sub-sequence are different. That is, 3 2 4 5 (3*2)=6 (2*4)=8 (4*5)=20 (3*2*4)= 24 (2*4*5)= 40
But 326 is not a colorful number as it generates 3 2 6 (3*2)=6 (2*6)=12.
You have to write a function that tells if the given number is a colorful number or not.

Solution

 1 public static boolean colorfulNumber(int num) {
 2     //if(num == null) return false;
 3 
 4     //convert num to arraylist
 5     List<Integer> al = new ArrayList<Integer>();
 6     while(num > 0) {
 7         al.add(num%10);
 8         num /= 10;
 9     }
10     System.out.println(al);
11     
12     //store res into hashset
13     Set<Integer> hs = new HashSet<Integer>();
14     for(int i=1; i<al.size(); i++) {
15         for(int j=0; j<al.size()-i+1; j++) {
16             int pro = al.get(j);
17             for(int k=j+1; k<j+i; k++) {
18                 pro = pro * al.get(k);
19             }
20             System.out.println(pro);
21             if(hs.contains(pro)) return false;
22             else hs.add(pro);
23         }
24     }
25     System.out.println(hs);
26     return true;
27 }

 

posted on 2014-11-21 09:55  SuperBo  阅读(221)  评论(0编辑  收藏  举报