Home » questions » Want can be the best logic for this?

Want can be the best logic for this?

2006-08-08 03:32:10, Category: Programming & Design
We have a string of digits, find the minimum number of additions required for the string to equal some target number. Each addition is the equivalent of inserting a plus sign somewhere into the string of digits. After all plus signs are inserted, evaluate the sum as usual. For example, consider the string "12" . With zero additions, we can achieve the number 12. If we insert one plus sign into the string, we get "1+2", which evaluates to 3. So, in that case, given "12", a minimum of 1 addition is required to get the number 3. As another example, consider "303" and a target sum of 6. The best strategy is not "3+0+3", but "3+03". You can do this because leading zeros do not change the result. Write a class SimpleSums that contains the method minMSums, which takes a String numbers and an int sum. The method should calculate and return the minimum number of additions required to create an expression from numbers that evaluates to sum. If this is impossible, return -1.

Answers

  1. Mr.Lee

    On 2006-08-08 03:47:15


    I guess following can help you give a number example "ab" and target "c" 1. Step 1: Identify the basic condition to break ur loop Basic condition to break ur loop If "ab" is the number and 'c' is the target if ( c < b ) //There is no point u can never obtain any result { result = -1; } Now this is the first check u have to do before u proceed further Now obtain ( ab -c ) and continue checking If ab -c yeiled say some 'df' Now check f < (b=b/10 ) and if it is possible keep incrementing the 'result' until ur result is not -1 ; so finally : U can loop until ur result is not -1 and everytime do a comparison with the units place I guess this helps...