Given a digit pattern with question marks and an N, find the smallest matching number with no leading zero that is divisible by N.
Medium5Dynamic programmingMathImplementationGreedyNo attempts yetTime limit1sMemory limit1024 MBCornelius Bakker was a pirate who also worked as an astronomer and a mathematician. He buried most of his fortune on the Caribbean island of Saint Basil, where the peak Pico Colombo is the usual landmark. Bakker vanished in 1617 when a hurricane caught his fleet of three ships. Before that last voyage he sent a letter to a niece in the Netherlands, giving the exact distance from Pico Colombo, due south, to the treasure.
Bakker did not want the letter to help a thief, so he did not write the distance itself. He multiplied it by a second number N and wrote the product D in the letter, together with the value of N and a description of the computation. Few robbers of that time knew how to divide two numbers. The letter reached Europe, but the niece had already entered a convent and never opened it.
Exactly four centuries later, Maria inherited a chest holding that nun's belongings and found the letter, still sealed. She is planning a trip to look for the treasure. The value of N is still readable, but moths have eaten part of D, so some of its digits are gone. The only clue she has is that the leftmost digit of D is not zero, because Bakker wrote that in the letter.
Given the damaged form of D and the value of N, find the smallest value D can have.
The first line contains a string S and an integer N (1≤N≤1000), separated by a space. S is not empty and its length is at most 1000. Each character of S is a decimal digit, or a question mark ? marking a position the moths ate. The first character of S is not 0, and at least one character is a question mark.
Consider every integer D that has exactly ∣S∣ digits, is a multiple of N, has a leading digit other than 0, and matches S at every position where S holds a digit. Print the smallest such D on one line. If no such D exists, print a single asterisk *.