Amazon Interview Question
SDE-2sCountry: United States
Below method should work:
public static int mulipleCustomLooping(int a, int b) {
int getresultat = 0;
for (int i = 0; i < a; i++) {
getresultat += b;
}
return getresultat;
}
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;
}
public static int multiply(int a,int b){
// flag to store if result is positive or negative
boolean isNegative = false;
// if both numbers are negative, make both numbers
// positive as result will be positive anyway
if (a < 0 && b < 0) {
a = -a;
b = -b;
}
// if only a is negative, make it positive
// and mark result as negative
if (a < 0) {
a = -a;
isNegative = true;
}
// if only b is negative, make it positive
// and mark result as negative
if (b < 0) {
b = -b;
isNegative = true;
}
int res =0;
// While second number doesn't become 1
while (b!=0){
// If second number becomes odd,
// add the first number to result
if((b&1)!=0){
res +=a;
}
// Double the first number
// and halve the second number
a = a <<1;
b = b >>1;
}
return (isNegative) ? -res : res;
}
public static int multiply(int a,int b){
// flag to store if result is positive or negative
boolean isNegative = false;
// if both numbers are negative, make both numbers
// positive as result will be positive anyway
if (a < 0 && b < 0) {
a = -a;
b = -b;
}
// if only a is negative, make it positive
// and mark result as negative
if (a < 0) {
a = -a;
isNegative = true;
}
// if only b is negative, make it positive
// and mark result as negative
if (b < 0) {
b = -b;
isNegative = true;
}
int res =0;
// While second number doesn't become 1
while (b!=0){
// If second number becomes odd,
// add the first number to result
if((b&1)!=0){
res +=a;
}
// Double the first number
// and halve the second number
a = a <<1;
b = b >>1;
}
return (isNegative) ? -res : res;
}
/*
i1 * i2
int result = 0;
add i1 to result i2 times.
*/
- Euihoon Seol October 18, 2020