In: Computer Science
using python without external libaries
Using integer arithmetic operators '+' and '-',
print all combinations that sum up to 'sum' by inserting the operators between digits in 'number'.
example for 'number=123456789' and 'sum = 0'
Print the output using the terminal:
Output should be exactly like this from 1 - 22
1 : +1+2-34-56+78+9=0
2 : +1-2-34+5+6+7+8+9=0
3 : +1-23-4-56-7+89=0
...
12 : -1+2+34-5-6-7-8-9=0
13 : -1+23+4+56+7-89=0
14 : -1-2+34+56-78-9=0
...
22 : -12-34+56+7-8-9=0
Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lab9;
import java.util.Scanner;
/**
*
* @author miracle
*/
public class Lab9 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter digit");
String number=sc.next();
System.out.println("Enter sum");
int sum=sc.nextInt();
insertOperators(number,sum);
}
static void verify(double sum, double previous, String number,
int target, String expr) {
if (number.length() == 0) {
if (sum + previous == target) {
System.out.println(expr + " = " + target);
}
} else {
for (int i = 1; i <= number.length(); i++) {
int current = Integer.parseInt(number.substring(0, i));
String remaining = number.substring(i);
verify(sum + previous, current, remaining, target, expr + " + " +
current);
verify(sum + previous, -current, remaining, target, expr + " - " +
current);
}
}
}
static void insertOperators(String number, int target) {
for (int i = 1; i <= number.length(); i++) {
String current = number.substring(0, i);
verify(0, Double.parseDouble(current), number.substring(i), target,
current);
}
}
}
Screenshot: