求123456789=x成立个数

最近,被面试到a, b, c, d, ... ,x,一组数中,通过加减法,能否得到某个数的算法。假设可以在a前面添加‘+’或者‘-’。

如果只有加减法,那么自然可以用位运算。比如:

1,2,3,4得到2,那么可以认为0000表示全是负书,0010表示第三个数是正数。

那么有:

public class AddSumToTarget {
	public static boolean AddSumTo(int[] nums, int target) {
		if (nums == null || nums.length == 0) {
			return false;
		}
		int n = nums.length;
		int k = 1 << n;
		for (int i = 0; i < k; ++i) {
			// for all cases
			int sum = 0;
			for (int j = 0; j < n; ++j) {
				// for the case, each number get a choice
				// (1 << j) & i) > 1: means that the jth number at case i(the
				// jth bit is the status of jth number)
				sum += (((1 << j) & i) > 0 ? 1 : -1) * nums[j];
			}
			if (sum == target) {
				return true;
			}
		}
		return false;
	}

	public static void main(String[] args) {
		System.out.println(AddSumTo(new int[] { 1, 2, 3, 4 }, 6));
		System.out.println(AddSumTo(new int[] { 1, 2, 3, 4 }, 2));
		System.out.println(AddSumTo(new int[] { 1, 2, 3, 4 }, 11));
	}
}

但是,近期看到华为有这样的题目,与上面的题目是类似的,但由于结果集不能用二进制计算,所以回溯做。

题目:

输入一个正整数X,在下面的等式左边的数字之间添加+号或者-号,使得等式成立。
1 2 3 4 5 6 7 8 9 = X
比如:
12-34+5-67+89 = 5
1+23+4-5+6-7-8-9 = 5
请编写程序,统计满足输入整数的所有整数个数。
输入:       正整数,等式右边的数字
输出:       使该等式成立的个数
样例输入:5
样例输出:21

public class Formulation {
	private static char[] flag = { ' ', '+', '-' };
	private static char[] f = { '1', ' ', '2', ' ', '3', ' ', '4', ' ', '5',
			' ', '6', ' ', '7', ' ', '8', ' ', '9' };
	private static int n = 0;

	public static void wayto(int x) {
		n = 0;
		wayto(1, x);
	}

	public static void wayto(int indice, int x) {
		if (indice >= 17) {
			n += check(x);
			return;
		}
		for (int i = 0; i < 3; ++i) {
			f[indice] = flag[i];
			wayto(indice + 2, x);
		}
	}

	private static int check(int x) {
		int a = 0, sum = 1, op = 1;
		int i = 1;
		while (i < 17 && f[i] == ' ') {
			sum = sum * 10 + f[i + 1] - '0';
			i += 2;
		}
		while (i < 17) {
			if (f[i] == ' ') {
				a = a * 10 + f[i + 1] - '0';
			} else {
				sum += op * a;
				a = f[i + 1] - '0';
				if (f[i] == '+') {
					op = 1;
				} else {
					op = -1;
				}
			}
			i += 2;
		}
		sum += op * a;
		return sum == x ? 1 : 0;
	}

	public static void main(String[] args) {
		wayto(123 - 45678 - 9);
		System.out.println(n);
		wayto(5);
		System.out.println(n);
		wayto(123456789);
		System.out.println(n);
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值