Hard 不用+号实现两个数之和 @CareerCup

例子:

759+674

1)不考虑进位:   323

2)只考虑进位:1110

3)两者之和:1433 递归求解c


package Hard;

/**
 * Write a function that adds two numbers. You should not use + or any arithmetic operators.

译文:

写一个Add函数求两个数的和,不能使用+号或其它算术运算符。
 *
 */
public class S18_1 {

	public static int add(int a, int b) {
		if (b == 0)
			return a;
		int sum = a ^ b; 				// add without carrying
		int carry = (a & b) << 1; // carry, but don’t add
		return add(sum, carry); // recurse
	}

	public static int randomInt(int n) {
		return (int) (Math.random() * n);
	}

	public static void main(String[] args) {
		for (int i = 0; i < 100; i++) {
			int a = randomInt(10);
			int b = randomInt(10);
			int sum = add(a, b);
			System.out.println(a + " + " + b + " = " + sum);
		}
	}
}


原文地址:https://www.cnblogs.com/fuhaots2009/p/3473293.html