[LeetCode] Add Strings

415. Add Strings

Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.

You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
public:
string addStrings(string num1, string num2) {
if(num1.length() < num2.length()) return addStrings(num2,num1);
int i = num1.length() - 1, j = num2.length() - 1, app = 0;
while(i >= 0 and j >= 0) {
int sum = (num1[i] & 0b1111) + (num2[j] & 0b1111) + app;
app = sum / 10;
sum %= 10;
num1[i] = sum | 0b110000;
i--,j--;
}
while(i >= 0 and app) {
int sum = (num1[i] & 0b1111) + app;
app = sum / 10;
sum %= 10;
num1[i] = sum | 0b110000;
i--;
}
if(i == -1 and app > 0) {
return "1" + num1;
} else {
return num1;
}
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/06/PS/LeetCode/add-strings/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.