You are given an integer N. You have to find smallest multiple of N which consists of digits 0 and 1 only. Since this multiple could be large, return it in form of a string.
Returned string should not contain leading zeroes.
For example,
For N = 55, 110 is smallest multiple consisting of digits 0 and 1. For N = 2, 10 is the answer.
I saw several related problems, but I could not find the problem with my code. Here is my code giving TLE on some cases even after using map instead of set.
#define ll long long
int getMod(string s, int A)
{
int res=0;
for(int i=0;i<s.length();i++)
{
res=res*10+(s[i]-'0');
res%=A;
}
return res;
}
string Solution::multiple(int A) {
if(A<=1)
return to_string(A);
queue<string>q;
q.push("1");
set<int>st;
string s="1";
while(!q.empty())
{
s=q.front();
q.pop();
int mod=getMod(s,A);
if(mod==0)
{
return s;
}
else if(st.find(mod)==st.end())
{
st.insert(mod);
q.push(s+"0");
q.push(s+"1");
}
}
}
Algorithm for Smallest Multiple of a Given Number For a given number n, traverse in the list formed and return the first number divisible by n. Create a list of string that will store the numbers made up of 9 and 0. Create a queue of string and push “9” to it, that is, the root of the tree.
Every number is a multiple of 1 and itself. Q. The smallest common multiple of a given set of numbers is called their .
2 multiplied by 1/100 gives 1/50. So, as we get closer and closer to zero, scaling the original amount gives a smaller and smaller number. Thus to make things consistent it ought to be that: 2 multiplied by 0 gives 0.
Interview Answers Two facts to note are: 1) Multiplies of 225 end in 00 25 50 75 2) A number is divisible by 9 if the digits sum to 9. Only those multiples ending in 00 could have only 1's and 0's. So, the smallest digit we can multiply 225 by to get 00 at the end is 4. That is, 225*4=900.
Here is an implementation in Raku.
my $n = 55;
(1 .. Inf).map( *.base(2) ).first( * %% $n );
(1 .. Inf)
is a lazy list from one to infinity. The "whatever star" *
establishes a closure and stands for the current element in the map
.
base
is a method of Rakus Num
type which returns a string representation of a given number in the wanted base, here a binary string.
first
returns the current element when the "whatever star" closure holds true for it.
The %%
is the divisible by
operator, it implicitly casts its left side to Int
.
Oh, and to top it off. It's easy to parallelize this, so your code can use multiple cpu cores:
(1 .. Inf).race( :batch(1000), :degree(4) ).map( *.base(2) ).first( * %% $n );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With