Pages

Wednesday 11 April 2012

Colorful Numbers

Problem : Determine whether a number is colorful or not. 263 is a colorful number because (2,6,3,2x6,6x3,2x3x6) are all different whereas 236 is not because (2,3,6,2x3,3x6,2x3x6) have 6 twice. So take all consecutive subsets of digits, take their product and ensure all the products are different

Solution :  
public class ColorfulNumbers {
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        String number = input.nextLine();
        Set<Integer> set = new HashSet<Integer>();
        for(int i=1;i<=number.length();i++)
        {
            for(int j=0;j+i<=number.length();j++)
            {
                int k =j;
                int prd = 1;
               
                while(k<j+i)
                {
                    prd = prd * (number.charAt(k)-'0');
                    k++;
                }
               
                if(set.contains(prd))
                {
                    System.out.println("Not colorful");
                    System.exit(0);
                }
                else
                {
                    set.add(prd);
                }
               
               
            }
        }
        System.out.println("Colorful");
       
    }
}

No comments:

Post a Comment