-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAdd_list.cpp
More file actions
51 lines (36 loc) · 1.18 KB
/
Add_list.cpp
File metadata and controls
51 lines (36 loc) · 1.18 KB
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
46
47
48
49
50
51
/*
Link : https://leetcode.com/problems/add-strings/
Problem Statement :
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
*/
//Solution :
class Solution {
public:
string addStrings(string num1, string num2) {
int i = num1.size() - 1;
int j = num2.size() - 1;
string res = "";
int carry = 0;
while(i>=0 || j>=0 || carry){
long sum = 0;
if(i >= 0){sum += (num1[i] - '0');i--;}
if(j >= 0){sum += (num2[j] - '0');j--;}
sum += carry;
carry = sum/10;
sum = sum % 10;
res += to_string(sum);
//carry += sum/10 -'0';
//res += sum%10 -'0';
}
reverseStr(res);
return res;
}
void reverseStr(string& str)
{
int n = str.length();
// Swap character starting from two
// corners
for (int i = 0; i < n / 2; i++)
swap(str[i], str[n - i - 1]);
}
};