InterviewBit - Colorful Number Solution - The Coding Shala

Home >> Programming Questions >> Colorful Number

InterviewBit Colorful Number Solution

In this post, you will learn how to solve InterviewBit's Colorful Number Problem and its solution in Java.

A colorful number is if a number can be broken into different contiguous sub-subsequence 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 the product of every digit of a contiguous subsequence is different.



Example:

N = 23
2 3 23
2 -> 2
3 -> 3
23 -> 6
this number is a COLORFUL number since the product of every digit of a sub-sequence is different.
Output: 1

Colorful number java Program

Approach:
We will use HashSet to check if the number is a colorful number or not. We will generate every possible number and find their product and will check if the current product is in HashSet or not.
Java Program: 

public class Solution {
    public int colorful(int A) {
        HashSet<Integer> check = new HashSet<Integer>();
        String str = Integer.toString(A);
        for(int i=0;i<str.length();i++){
            int product = 1;
            for(int j=i; j<str.length();j++){
                int num = str.charAt(j) - '0';
                product *= num;
                if(check.contains(product)) return 0;
                check.add(product);
            }
        }
        return 1;
    }
}


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Introduction to Kotlin Programming Language for Backend Development - The Coding Shala

Java Program to Reverse a String using Stack - The Coding Shala