For Given Number
Number is COLORFUL number if product of every digit of a contiguous subsequence is different.
Return 0/1
Solution
Approach is to explore all combinations and check product of the all digits. Hashing can be helpful here to store product value of previous explored combination.
Code
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.util.HashSet; public class ColorFulNum { public static void main(String[] args) { System.out.println(new ColorFulNum().colorful(3245)); } public int colorful(int a) { String A = Integer.toString(a); HashSet<Integer> set = new HashSet<Integer>(); int prod = 0; //Exploring all combinations for(int i = 0; i < A.length(); i++) { prod = 1; for(int j = i; j < A.length(); j++ ){ prod *= A.charAt(j)-'0'; //Check if Product value already present. if(set.contains(prod)) return 0; else set.add(prod); } } return 1; } } |
Output
We acknowledge you to write a comment if you have a better solution or having any doubt on the above topic.