问题描述:
已知所有砝码重量均为3的倍数,且所有重量的砝码有且只有一个
要求输出1到n的所有物品的称重方式
解题思路:
| 物品重量 | 砝码 |
| 1 | 1 |
| 2 | 3 - 1 |
| 3 | 3 |
| 4 | 3 + 1 |
| 5 | 9 - 3 - 1 |
| ... | ... |
经过对比发现,若物品重量刚刚超过了较大砝码的一半,则需要减去后一位数,反之则加.
代码实现:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int w = input.nextInt(); //所称物体的重量
for (int i = 1; i <= w; i++) { //i为所需称重的物品重量
System.out.println(i + ": " + fun(i));
}
input.close();
}
public static String fun(int w) {
int i = 1;
while(i < w) i *= 3;
if (w == i) return i + "";
if (w <= i/2) return i/3 + "+" + fun(w - i/3);
return i + "-" + reve(fun(i - w));
}
private static String reve(String str) {
str = str.replace("+", "#");
str = str.replace("-", "+");
str = str.replace("#", "-");
return str;
}
}
运行测试:

github平台代码链接:https://github.com/striner/javaCode/blob/master/Weigher%20weighing

这篇博客介绍了如何解决一个经典算法问题——天秤称重,问题要求使用3的倍数重量的砝码称出1到n的所有物品重量。解题关键在于当物品重量超过较大砝码一半时,需要减去后一位数。博主提供了详细的解题思路及Java代码实现,并在GitHub上分享了完整代码链接。

608

被折叠的 条评论
为什么被折叠?



