編寫一個在1,2,…,9(順序不能變)數字之間插入+或-或什麼都不插入,使得計算結果老是100的程序

public class Get100Demo {

	public static void main(String[] args) {
		int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		int total = power(3, nums.length - 1);

		for (int o = 0; o < total; o++) {
			StringBuffer buffer = new StringBuffer();
			buffer.append(nums[0]);
			int result = 0;
			int temp = nums[0];
			for (int i = 1; i < nums.length; i++) {
				int bit = getBitNum(i, o);
				if (bit == 0) {
					buffer.append(" + ");
					result += temp;
					temp = nums[i];
				} else if (bit == 1) {
					buffer.append(" - ");
					result += temp;
					temp = -nums[i];
				} else {
					if (temp > 0)
						temp = 10 * temp + nums[i];
					else
						temp = 10 * temp - nums[i];
				}
				buffer.append(nums[i]);
			}
			result += temp;
			buffer.append(" = ");
			buffer.append(result);

			if (result == 100)
				System.out.println(buffer);
		}
	}

	public static int getBitNum(int index, int number) {
		return (number / power(3, index - 1)) % 3;
	}

	public static int power(int number, int index) {
		return index > 0 ? number * power(number, index - 1) : 1;
	}
}

如下是運行結果:java

1 + 23 - 4 + 56 + 7 + 8 + 9 = 100
12 + 3 - 4 + 5 + 67 + 8 + 9 = 100
1 + 2 + 34 - 5 + 67 - 8 + 9 = 100
1 + 2 + 3 - 4 + 5 + 6 + 78 + 9 = 100
123 - 4 - 5 - 6 - 7 + 8 - 9 = 100
123 + 45 - 67 + 8 - 9 = 100
1 + 23 - 4 + 5 + 6 + 78 - 9 = 100
12 - 3 - 4 + 5 - 6 + 7 + 89 = 100
12 + 3 + 4 + 5 - 6 - 7 + 89 = 100
123 - 45 - 67 + 89 = 100
123 + 4 - 5 + 67 - 89 = 100
相關文章
相關標籤/搜索