藍橋-天秤稱重問題

經典算法之天秤稱重問題

問題描述:
已知所有砝碼重量均爲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;
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章