Hardは+番号を使わずに2つの数の和@CareerCupを実現
819 ワード
例:
759+674
1)キャリーを考慮しない: 323
2)キャリーのみ考慮:1110
3)両者の和:1433再帰解c
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);
}
}
}