import java.util.*; /* * Jonny has solved math expression in the form: * 4 + 12 + 3 = 19 * but by mistake he deleted the pluses. Write a program that find out * the location of pluses in the expression that add up to v. * 4 1 2 3 = 19 ??? * The number of the pluses must be minimum */ public class JonnyHatesMathAlot { //given numbers private String ex; //target value private int value; public JonnyHatesMathAlot(String ex, int v ){ this.ex = ex; this.value = v; } public static void main(String[] args){ //test case 1 String str = "15442147612367219875"; for(int i=472 ; i < 1000 ;i+=10){ JonnyHatesMathAlot jhm = new JonnyHatesMathAlot(str,i); jhm.process(); } //test case 2 str = "12310"; JonnyHatesMathAlot jhm = new JonnyHatesMathAlot(str,25); jhm.process(); } public void process(){ //compute the number of choices to insert pluses long N = (long)Math.pow( 2 , this.ex.length() - 1); int exLen = this.ex.length(); StringBuffer sb = new StringBuffer(); //list of possible solutions List solutions = new ArrayList(); int minNumPluses = this.value; for(int i=0;i=0;index--){ int rmd = (int) ( 1 & mask); mask = mask >> 1; sb.insert(0,this.ex.charAt(index)); if(rmd == 1) { sb.insert(0,'+'); numPluses++; } } //evaluate the expression... if(sumUP2Value(sb.toString())){ if(minNumPluses > numPluses){ solutions.clear(); minNumPluses = numPluses; solutions.add(sb.toString()); }else if(minNumPluses == numPluses){ solutions.add(sb.toString()); } } sb.delete(0, sb.length()); } if(solutions.size()==0){ System.out.println("Impossible for value:" + this.value); }else for(int i=0;i nLen ) return -1; int i = Integer.parseInt(s); sum+=i; } return sum; } }