A decimal number is called a binary digit number if its digits are binary. For example, 102 is not a binary digit number and 101 is.
We are given a decimal number N, we need to find the smallest multiple of N which is a binary digit number,
Input : N = 2 Output: 10 Explanation: 10 is a multiple of 2. Note that 5 * 2 = 10 Input : N = 17 Output : 11101 Explanation: 11101 is a multiple of 17. Note that 653 * 17 = 11101
We can solve this problem using BFS, every node of the implicit graph will be a binary digit number and if the number is x, then its next level node will be x0 and x1 (x concatenated with 0 and 1).
In starting, we will push 1 into our queue, which will push 10 and 11 into queue later and so on, after taking the number from the queue we’ll check whether this number is multiple of a given number or not, if yes then return this number as result, this will be our final result because BFS proceeds level by level so the first answer we got will be our smallest answer also.
In the below code binary digit number is treated as a string, because for some number it can be very large and can outside the limit of even long, mod operation on number stored as the string is also implemented.
The main optimization tweak of code is using a set for modular value, if a string with the same mod value has previously occurred we won’t push this new string into our queue. The reason for not pushing new string is explained below,
Let x and y be strings, which gives the same modular value. Let x be the smaller one. let z be another string which when appended to y gives us a number divisible by N. If so, then we can also append this string to x, which is smaller than y, and still get a number divisible by n. So we can safely ignore y, as the smallest result will be obtained via x only.
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.