蓝桥-天秤称重问题

经典算法之天秤称重问题

问题描述:
已知所有砝码重量均为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;
	}
}

猜你喜欢

转载自blog.csdn.net/qq_35394891/article/details/84780742