## Amazon Interview Question

SDE-2s**Country:**United States

```
public static int multiply(int i1, int i2) {
boolean isPositive = false;
if(i1==0 || i2==0) return 0;
if(i1<0 & i2<0) isPositive=true;
else if(i1>0 & i2>0) isPositive=true;
if(i1<0) i1 = ~i1+1;
if(i2<0) i2 = ~i2+1;
int acc = i1;
for(int i=2; i <= i2; i++) acc = add(acc, i1);
return isPositive ? acc : ~acc+1;
}
public static int add(int i1, int i2){
final int mask = 1;
int subsum=0, result=0, pos=0;
boolean carryOver=false;
while(i1>=0 || i2>=0){
final int digitA = i1 & mask, digitB = i2 & mask;
/*
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
*/
subsum = digitA ^ digitB;
if(carryOver) subsum ^= 1;
carryOver = (carryOver && (digitA == 1 || digitB == 1)) |
(!carryOver && digitA == digitB && digitB == 1);
i1 >>= 1; i2 >>= 1;
subsum <<= pos;
pos++;
result |= subsum;
if(i1 == i2 && i2 == 0 && !carryOver) break;;
}
return result;
}
```

/*

i1 * i2

int result = 0;

add i1 to result i2 times.

*/

```
public int multiple (int i1, int i2) {
int i = 0;
int result = 0;
while (i2 > i) {
result = add(result, i1);
i = add(i, 1);
}
return result;
}
public int add(int i1, int i2) {
// iterate until there is no carry
while (i2 != 0) {
// carry contains common set bits of i1 and i2
int carry = i1 & i2;
// sum of bits of i1 and i2 where at least either of i1 and i2 bits is 0
i1 = i1 ^ i2;
// carry is shifted by one so that adding it to i1 gives the required sum
i2 = carry << 1;
}
return i1;
}
```

Below method should work:

- Yogesh shukla July 23, 2020public static int mulipleCustomLooping(int a, int b) {

int getresultat = 0;

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

getresultat += b;

}

return getresultat;

}