For given numbers A and B in function Aplusb, return the sum of them.
Note
You don't need to parse the input and output. Just calculate and return.
Example
If A=1 and b=2 return 3
Challenge
Can do it with out + operation?
Clarification
is a and B both 32-bit integers?
-Yes.
Analysis:
Use bit manipulation.
Solution 1:
Caluclate every bit.
1 classSolution {2 /*3 * param a:the First integer4 * param b:the Second integer5 * return:the sum of a and B6 */7 Public intAPLUSB (intAintb) {8 intres = 0;9 intCarry = 0;Ten for(inti=0;i<32;i++){ One intA1 = A & 1; A intB1 = B & 1; - intval = 0; - if(a1==1 && b1==1 && carry==1){ theval = 1; -Carry = 1; -}Else if((a1==1 && b1==1) | | (a1==1 && carry==1) | | (B1==1 && Carry==1) ) { -val = 0; +Carry = 1; -}Else if(a1==1 | | b1==1 | | carry==1) { +val = 1; ACarry = 0; at}Else { -val = 0; -Carry = 0; - } -val = Val <<i; -res = Res |Val; inA = a >> 1; -b = B >> 1; to } + - returnRes; the * } $};
Solution 2:
For a + B on any base, we can treat the plus as part:1. A + b without carry; 2. The carry generated by a +b. The a+b then equals to Part 1 plus Part 2. If Part1+part2 generates more carry, we can then repeat this procedure, until there is no carry.
1 classSolution {2 /*3 * param a:the First integer4 * param b:the Second integer5 * return:the sum of a and B6 */7 Public intAPLUSB (intAintb) {8 while(b!=0){9 intcarry = A & B;//their carry (actuall, need to move to right by one bit.TenA = A^b;//their plus result without carry. Oneb = Carry << 1; A } - returnA; - } the};
Lintcode-a+b problem