Add each digit, and carry the one as necessary
Sum ONLY:
759
674
___
323
9 = 1001
4 = 0100
----------
13 = 1101 = 9^4
====> XOR
carry ONLY:
7 5 9
6 7 4
____
1110
9 = 1001
4 = 0100
----------
0 = 0000 = 9&4
====> AND
2 = 0010
10 = 1010
-------------
12 = 1100
2^10 = 1000 =8
2&10= 0010
0010 << 1 = 0100 =4
8^4 = 1000^0100 = 1100 = 12
2. Implementation
public int addTwoNumber_No_Arithm(int a, int b) { if (b==0) return a; // no carry int sum = a^b; // add without carrying int carry = (a&b)<<1; // carry, but no add return addTwoNumber_No_Arithm(sum, carry); }3.Similar Ones
No comments:
Post a Comment