Write a function that given a string of digits and a target value, prints where to put +'s and *'s between the digits so they combine exactly to the target value. note there may be more than one answer, it doesn' t matter which one you print.
Examples:
"1231231234", 11353-> "12*3 + 1 + 23*123*4"
"3456237490", 1185-> "3*4*56 + 2 + 3*7 + 490"
"3456237490", 9191-> "no solution"
Solution 1: (I don't want to come up with it) for reference (using the exhaustive method)
Code
Static void main (string [] ARGs)
{
Check ("22", 1/* shoshould start from 1 */, 4 );
Check ("3456237490", 1/* shoshould start from 1 */, 1185 );
Check ("3456237490", 1/* shoshould start from 1 */, 9191 );
}
Public static void check (string STR, int index, int expectedresult)
{
String teststr = string. empty;
For (INT I = index; I <Str. length; I ++)
{
// Check index +
Teststr = Str. insert (I, "+ ");
If (evaluate (teststr) = expectedresult)
Console. writeline (teststr + "=" + expectedresult );
Check (teststr, I + 2, expectedresult );
// Check Index *
Teststr = Str. insert (I ,"*");
If (evaluate (teststr) = expectedresult)
Console. writeline (teststr + "=" + expectedresult );
Check (teststr, I + 2, expectedresult );
}
}
Public static long evaluate (string expression)
{
List <string> STRs = new list <string> ();
String STR = string. empty;
Foreach (char CH in expression. tochararray ())
{
Switch (CH)
{
Case '*':
If (STR! = String. Empty)
STRs. Add (STR );
STR = string. empty;
STRs. Add ("*");
Break;
Case '+ ':
If (STR! = String. Empty)
STRs. Add (STR );
STR = string. empty;
STRs. Add ("+ ");
Break;
Default:
STR + = CH. tostring ();
Break;
}
}
If (STR! = String. Empty)
STRs. Add (STR );
Stack <long> intstack = new stack <long> ();
For (INT I = 0; I <STRs. Count; I ++)
{
Switch (STRs [I])
{
Case "+ ":
Break;
Case "*":
Long before = intstack. Pop ();
Long next = long. parse (STRs [++ I]);
Intstack. Push (before * Next );
Break;
Default:
Intstack. Push (long. parse (STRs [I]);
Break;
}
}
Long result = 0;
While (intstack. Count> 0)
Result + = intstack. Pop ();
Return result;
}
}