Given two positive numbers which are represented in strings, return the sum, difference, product, quotient and remainder of the two numbers.
A solution is to have the string converted to an array where digits are store in a reversed order and then do the calculation on each digit.
I. a + b
The implementation is quite straight-forward. Just be care of the carry.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21public List<Integer> add(List<Integer> num1, List<Integer> num2) {
List<Integer> sum = new ArrayList<>();
int i = 0;
int carry = 0;
while (i < num1.size() || i < num2.size()) {
int n = carry;
if (i < num1.size()) {
n += num1.get(i);
}
if (i < num2.size()) {
n += num2.get(i);
}
i++;
sum.add(n % 10);
carry = n / 10;
}
if (carry > 0) {
sum.add(carry);
}
return sum;
}
Leetcode: 2. Add Two Numbers.
II. a - b
Simplar to a + b, but be aware of the case when a is smaller than b. And don’t forget to remove the leading 0 in the difference.
1 | // num1 must be larger than num2 |
III. a * b
The solution is to mimic the process of doing multiplication, but be aware of the the index.
1 | private List<Integer> multiple(List<Integer> num1, List<Integer> num2) { |
LeetCode: 43. Multiply Strings
IV. a / b and a % b
The idea is to use subtraction - repeat the process of a minus b until a < b. But this whole process is time consuming. To improve performance, we don’t have to do a - b each time, but we can try something like a - b*10. For example, a = 2981, b = 13, because the difference between the length of a and b is 2, so the dividend can be initailized to be 1300, and when the divisor become less than dividend, a 0 can be removed from the dividend, as shown in the table below. This is actually how we do subtraction.
divisor | dividend | quotient | remainder |
---|---|---|---|
2981 | 1300 | 100 | 1681 |
1681 | 1300 | 200 | 381 |
381 | 130 | 210 | 251 |
251 | 130 | 220 | 121 |
121 | 13 | … | … |
1 | // num2 cannot be a zero |