Colorful Numbers | Algorithms
Objective: Given a number, find out whether its colorful or not.
Colorful Number: When in a given number, product of every digit of a sub-sequence are different. That number is called Colorful Number. See Example
Read full article from Colorful Numbers | Algorithms
Objective: Given a number, find out whether its colorful or not.
Colorful Number: When in a given number, product of every digit of a sub-sequence are different. That number is called Colorful Number. See Example
- Insert all the digits into hast table
- Create a powerset of digits except empty set (Power Set)
- Multiply all the digits in the individual powerset and insert into Hash Table.
- If any point, number already present in the Hash table, return false
- No need to use hashtmap, hashset will just work.
Hashtable<Integer, Integer> ht =
new
Hashtable<>(); // use hashmap or just hashset.
boolean
[] used;
// for creating powerset, every digit, either
//it will be selected or not
public
int
[] getdigits(
int
Number){
int
length = String.valueOf(Number).length();
int
A [] =
new
int
[length];
int
counter = length-
1
;
//start filling from the end
while
(Number>
0
){
int
x = Number%
10
;
Number = Number/
10
;
A[counter]=x;
counter--;
}
return
A;
}
public
boolean
getColorFul(
int
Number){
ht.clear();
int
[] A = getdigits(Number);
used =
new
boolean
[A.length];
return
powerSet(A, used,
0
);
}
public
boolean
powerSet(
int
[] A,
boolean
[] used,
int
x){
if
(x==used.length-
1
){
used[x] =
false
;
boolean
b = insertInHash(A, used);
if
(b){
used[x] =
true
;
return
insertInHash(A, used);
}
else
{
return
false
;
}
}
used[x] =
false
;
boolean
p = powerSet(A, used, x+
1
);
used[x] =
true
;
return
p & powerSet(A, used, x+
1
);
}
public
boolean
insertInHash(
int
[] A,
boolean
[] used){
int
Sum=
0
;
for
(
int
i =
0
;i<used.length;i++){
if
(used[i]){
if
(Sum==
0
){
Sum =A[i];
}
else
{
Sum*=A[i];
}
}
}
if
(ht.containsKey(Sum)){
return
false
;
}
else
{
ht.put(Sum,
1
);
return
true
;
}
}