Amazon Interview Question

How would you implement integer division if your language did not offer it.

Interview Answers

Anonymous

Jan 24, 2011

#Assumes positive numbers def divide(num, divide_by) answer = 0 return answer if divide_by == 0 while(num >= divide_by) num = num - divide_by answer = answer + 1 end answer end puts divide(10,0)

5

Anonymous

Jan 5, 2014

Simpler version (assuming you are allowed to use multiplication), just compute the sign at the end and multiply: function divide(a, b){ if(b == 0) throw "Cannot divide by zero"; var remainder = Math.abs(a); var dividend = Math.abs(b); var result = 0; while(remainder >= dividend){ result++; remainder -= dividend; } if(result > 0 && a*b < 0) result *= -1; return result; }

1

Anonymous

Jan 8, 2025

<p></p><h5>test1324</h5>

Anonymous

Apr 12, 2012

I think this is all you need, as the question asks for integer division I.e. 2 integer inputs to provide integer output 3 / 4 = 0 (dividend is less than the divisor) 2 / 1 = 2 (divisor is 1) 4 / 2 = 2 (divisor is a factor) 7 / 5 = 1 (dividend is greater than divisor) Note: solution below is for positive integers public static double divide(int dividend, int divisor) { int remainder = dividend; int count = 0; while (remainder > divisor) { remainder -= divisor; count++; } return count; }

1

Anonymous

Apr 12, 2012

EDIT: To also handle divide by zero and negative numbers public static int divide(int dividend, int divisor) throws ArithmeticException{ int remainder = dividend; int count = 0; if (divisor == 0) { throw new ArithmeticException("Divide by 0"); } if (remainder > 0 && divisor = divisor) { remainder -= divisor; count--; } } else if (remainder 0) { remainder *= -1; while (remainder >= divisor) { remainder -= divisor; count--; } } else if (remainder = divisor) { remainder -= divisor; count++; } } else { while (remainder >= divisor) { remainder -= divisor; count++; } } return count; }

Anonymous

May 28, 2009

http://www.bearcave.com/software/divide.htm

1