-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddstrings.cpp
45 lines (37 loc) · 1.02 KB
/
addstrings.cpp
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Solution {
public:
string addStrings(string num1, string num2) {
int rem, len, len1 = num1.length(), len2 = num2.length();
string s, result="";
char tmp;
if(len1 < len2) {
len = num1.length();
s = num2;
rem = num2.length();
} else {
len = num2.length();
s = num1;
rem = num1.length();
}
int curr, temp, carry = 0;
for(int i=0; i<len; i++) {
curr = (num1[len1-1-i] - '0') + (num2[len2-1-i] - '0') + carry;
temp = curr%10;
carry = curr/10;
tmp = temp + '0';
result = tmp+result;
}
for(int i=rem-len-1; i>=0; i--) {
curr = (s[i] - '0') + carry;
temp = curr%10;
carry = curr/10;
tmp = temp + '0';
result = tmp+result;
}
if (carry) {
tmp = carry + '0';
result = tmp + result;
}
return result;
}
};