);
}
}
if(a[h]!=0){
if(a[h]>0){
System.out.print("+"+a[h]);
}
else{
System.out.print(a[h]);
}
}
}
}
}
}
}
}
System.out.println();
look();
}else{
System.out.println("输入有误,请检查!");
look();
}
}
}
以下是所谓的递归算法,这里关键是弄清楚fact()方法的原理。
import java.util.Scanner;
public class Balance2 {
static int data[]={1,3,9,27,81};
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
deep(scanner.nextInt(),"");
}
//以下调用递归
private static void deep(int s,String str){
//当S变成零则输出结果
if(s==0){
System.out.println(str.substring(1));
}
//当s>0时,还应该添加砝码
else if(s>0){
int temp=s-fact(s);//调用fact()方法
deep(temp,str+"+"+fact(s));//调用方法自己,加号添加砝码
}
//当s<0时,应该减去砝码
else if(s<0){
int temp=s+fact(s);
deep(temp,str+"-"+fact(s));//调用方法自己
}
}
//以下是递归的算法:当物体的质量大于比它质量小的砝码的所有砝码质量和的时候选择大砝码。
private static int fact(int i) {
i=Math.abs(i);//返回 i 值的绝对值
int flag=0;//标记
int sum=0;//小砝码质量和
for(int j=1;j<5;j++){
//这个条件找到物体的质量的范围
if(i>data[j-1] && i<data[j] || i>=data[j]){
sum+=data[m];
}
if(i>sum){
flag=j;
}else{
flag=j-1;
}
}
}
return data[flag];
}
}
作者: 柏占肖 时间: 2012-9-28 11:38
- import java.util.Scanner;
- public class FaMa {
- public static void main(String[] args) {
- int[] faMa = { 1, 3, 9, 27, 81 };
- int[] faMa2 = new int[5];
- int sum;
- while (true) {
- Scanner scanner = new Scanner(System.in);
- sum = scanner.nextInt();
- if (sum > 121 || sum < 1) {
- System.out.println("请输入1到121之间的数字");
- continue;
- }
- getResult(faMa, faMa2, 0, sum);
- }
- }
- public static void getResult(int[] faMa1, int[] faMa2, int index, int sum) {
- if (5 == index) {
- int cont = 0;
- for (int i = 0; i < index; i++) {
- cont += faMa2[i];
- }
- if (cont == sum) {
- int i;
- for (i = index - 1; faMa2[i] == 0; i--) {
- }
- System.out.print(faMa2[i--]);
- for (; i >= 0; i--) {
- if (0 < faMa2[i]) {
- System.out.print("+" + faMa2[i]);
- } else if (0 > faMa2[i]) {
- System.out.print(faMa2[i]);
- }
- }
- System.out.println();
- }
- return;
- }
- faMa2[index] = faMa1[index];
- getResult(faMa1, faMa2, index + 1, sum);
- faMa2[index] = -faMa1[index];
- getResult(faMa1, faMa2, index + 1, sum);
- faMa2[index] = 0;
- getResult(faMa1, faMa2, index + 1, sum);
- }
- }
复制代码 这是第二届“蓝桥杯”全国软件大赛的C语言专科组四川初赛题的最后一题,我参加的是第三届,这题早就做过了,所以这次写起来是一气呵成,呵呵……你同学是不是要在为参加第四届做准备哦,
作者: 寇龙飞 时间: 2012-9-28 16:49
占个位置。。。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |