415. Add Strings
Difficulty: Easy
Topics: String
Similar Questions:
Problem:
Given two non-negative integers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
num1
and num2
is < 5100.num1
and num2
contains only digits 0-9
.num1
and num2
does not contain any leading zero.Solutions:
class Solution {
public:
string addStrings(string num1, string num2) {
string ret;
int carry = 0;
int i1 = num1.length() - 1;
int i2 = num2.length() - 1;
while (carry != 0 || i1 >= 0 && i2 >= 0) {
int value = carry + (i1 >= 0 ? num1[i1--] - '0': 0) + (i2 >= 0 ? num2[i2--] - '0' : 0);
ret.push_back(value % 10 + '0');
carry = value / 10;
}
reverse(ret.begin(), ret.end());
if (i1 >= 0) {
ret = num1.substr(0, i1 + 1) + ret;
}
if (i2 >= 0) {
ret = num2.substr(0, i2 + 1) + ret;
}
return ret;
}
};