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

来源:互联网 发布:美国通胀数据公布时间 编辑:程序博客网 时间:2024/06/10 14:22

例子:

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 carryingint carry = (a & b) << 1; // carry, but don’t addreturn 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);}}}


0 0