* * Weight weighing 5 weights with the balance weighing, we want to use as little weight combination as possible to weigh as much as possible. If there are only 5 weights, the weight is 1,3,9,27,81.
They can be combined to weigh any number of integers from 1 to 121 (weights are allowed in around two disks).
This topic requires programming implementation: to the user given the weight, give a weight combination scheme.
For example: User input: 5 program output: 9-3-1 user input: 19 program output: 27-9+1 requires the combination of the program output is always large number in the first decimal.
You can assume that the user's input number conforms to the range 1~121.
* * Import Java.util.Scanner; public class Demo07 {public static void F (int n) {int[] sign = new int[]{-1,0,1};//define symbol StringBuffer SB = new STR
Ingbuffer ();
for (int a:sign) {to (int b:sign) {for (int c:sign) {to (int d:sign) {for (int e:sign) {int i = a*1;
int j = b*3;
int k = c*9;
int L = d*27;
int m = e*81; if (i+j+k+l+m==n) {//Find result//If not 0, add element and add "+" sb.append before "positive number" (m!=0? M>0? "
+ "+m:m"): ""); Sb.append (l!=0?) ( L>0? "
+ "+l:l"): ""); Sb.append (k!=0?) ( K>0? "
+ "+k:k"): ""); Sb.append (j!=0?) ( J>0? "
+ "+j:j"): ""); Sb.append (i!=0?) ( I>0? "
+ "+i:i"): ""); Sb.deletecharat (0);
Remove the "+" number of the first element;
System.out.println (SB);
Return
} '}}}} ' public static void main (string[] args) {Scanner scan = new Scanner (system.in);
SYSTEM.OUT.PRINTLN ("Input weight (1 to 121) of any integer"); int n = scan.nextint ();
Input weight f (n); }
}
Run Result:
Enter a weight (1 to 121) between any
integer
27-9+1