# Java Solution

• ``````public class Solution {
public int getSum(int a, int b) {
boolean carryBit = false;
int bit = 1;
int answer = 0;

for(int i = 0; i < 32; i++){

boolean aMask = (a & bit) == bit;
boolean bMask = (b & bit) == bit;

//carryBit, bMask, and aMask are all 1
//We therefore put a 1 in this place and carry a 1
if(carryBit && bMask && aMask){
carryBit = true;
answer |= bit;
bit = bit << 1;
continue;
}

//two of carryBit, bMask, and aMask are 1
//We therefore put a 0 in this place and carry a 1
if((carryBit && bMask) || (carryBit && aMask)
|| (aMask && bMask)){
carryBit = true;
bit = bit << 1;
continue;
}

//only one of carryBit, bMask, and aMask are 1
//We therefore put a 1 in this place and carry a 0
if(carryBit || bMask || aMask){
carryBit = false;
answer |= bit;
bit = bit << 1;
continue;
}

//All of carryBit, bMask, and aMask are 0
//We therefore put a 0 in this place and carry a 0
carryBit = false;
bit = bit << 1;
}

return answer;

}
}
``````

This is a software implementation of a standard 32 bit hardward adder.

• I don't know if i++ is not a "add"

consider

int result = b;
for(int i = 0; i < a; i++)
{
result++;
}
return result;

so if ++ not add , why use bit compute?

• @heavengyk Using the ++ operator clearly violates the constraints of the question. You can think of i++ as equivalent to i = i + 1 which is clearly not allowed.

• @mviele said in Java Solution:

constraints

Yeah , I mean your code has ++ to.

"for(int i = 0; i < 32; i++)"

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.