例子:

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);
		}
	}
}


 

 

相关文章:

  • 2021-05-23
  • 2022-12-23
  • 2021-12-08
  • 2021-11-27
  • 2021-05-02
  • 2021-09-18
  • 2022-01-05
猜你喜欢
  • 2021-06-21
  • 2021-10-12
  • 2021-05-28
  • 2021-07-15
  • 2022-12-23
  • 2021-08-27
  • 2021-08-19
相关资源
相似解决方案