Find the Quotient and Remainder
Solve this ProblemEasy5 min
Topics
BasicsVariablesMath
Companies
TCSInfosysWipro
Given a non-negative
dividend and a positive divisor, return [quotient, remainder]: how many whole times the divisor fits into the dividend, and what is left over.
Division with a remainder is the long division you learnt at school, and it underlies many later problems (digit extraction, even/odd checks, clock arithmetic). The quotientQuotientThe number of whole times the divisor fits into the dividend. and remainderRemainderWhat is left of the dividend after taking away every whole group of the divisor. always satisfy dividend = quotient × divisor + remainder. The first solution literally removes groups one at a time; the second lets the / and % operators do it instantly.
Test Case 1:
Input:dividend = 17, divisor = 5
Output:[3, 2]
Explanation:Three groups of 5 make 15, and 2 is left over.
Test Case 2:
Input:dividend = 4, divisor = 9
Output:[0, 4]
Explanation:The divisor is bigger, so no whole group fits and everything is left over.
Constraints
- ◆
0 ≤ dividend ≤ 1000000 - ◆
1 ≤ divisor ≤ 1000000
Try the Dry Run
Approach & Solutions
Repeated SubtractionBrute
Division is repeated subtraction. Keep taking divisor away from what remains, counting each time, until what remains is smaller than divisor. The count is the quotient and what remains is the remainder. It is slow for large quotients, but it shows exactly what / and % mean.
Time
O(dividend / divisor)Space
O(1)Java
class Solution {
public int[] quotientAndRemainder(int dividend, int divisor) {
int quotient = 0;
int remaining = dividend;
while (remaining >= divisor) {
remaining -= divisor;
quotient++;
}
return new int[] {quotient, remaining};
}
}Division and Modulo OperatorsOptimal
The / operator on two ints gives the quotient directly and the % operator gives the remainder, each in one step no matter how big the numbers are. Python writes the whole-number division as //, and JavaScript uses Math.floor(dividend / divisor).
Time
O(1)Space
O(1)Java
class Solution {
public int[] quotientAndRemainder(int dividend, int divisor) {
int quotient = dividend / divisor;
int remainder = dividend % divisor;
return new int[] {quotient, remainder};
}
}