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
- Check if a given string is palindrome or not
- Leetcode - climbing stairs
- Hackerrank - Happy new year chaos
- Hackerrank - minimum swaps 2
- Leetcode - jewels and stones
Comments
Post a Comment