코드 >>
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
|
#include <iostream>
#include <string>
#include <algorithm>
#include <cstdlib>
using namespace std;
string addStrings(string num1, string num2)
{
string temp;
int sSize = (int)num1.size();
int pSize = (int)num2.size();
int i = sSize - 1;
int j = pSize - 1;
int carry = 0;
int value = 0;
int sDigit = 0;
int pDigit = 0;
while ((i >= 0 && j >= 0))
{
sDigit = (int)(num1[i] - '0');
pDigit = (int)(num2[j] - '0');
int tempInt = sDigit + pDigit + carry;
value = tempInt % 10;
temp.push_back((char)(value) + '0');
carry = tempInt / 10;
i--;
j--;
}
if (j > i)
{
while (j >= 0)
{
int tempInt = (int)(num2[j] - '0') + carry;
value = tempInt % 10;
//std::cout << (char)((int)(p[j] - '0') + carry) + '0' << std::endl;
temp.push_back((char)(value) + '0');
carry = tempInt / 10;
j--;
}
if (carry == 0)
{
reverse(temp.begin(), temp.end());
return temp;
}
else
{
temp.push_back((char)carry + '0');
reverse(temp.begin(), temp.end());
return temp;
}
reverse(temp.begin(), temp.end());
return temp;
}
else if (j == i)
{
if (carry == 0)
{
reverse(temp.begin(), temp.end());
return temp;
}
else
{
temp.push_back((char)carry + '0');
reverse(temp.begin(), temp.end());
return temp;
}
}
else
{
while (i >= 0)
{
int tempInt = (int)(num1[i] - '0') + carry;
value = tempInt % 10;
temp.push_back((char)(value)+'0');
carry = tempInt / 10;
i--;
}
if (carry == 0)
{
reverse(temp.begin(), temp.end());
return temp;
}
else
{
temp.push_back((char)carry + '0');
reverse(temp.begin(), temp.end());
return temp;
}
reverse(temp.begin(), temp.end());
return temp;
}
}
int main()
{
string p = "999918237891239";
string s = "999123812";
std::cout << addStrings(p, s) << std::endl;
return 0;
}
|
'C' 카테고리의 다른 글
c++ leetcode O(N) solution Longest Substring Without repetition (0) | 2021.07.07 |
---|---|
c++ leetcode 49 Group Anagrams solutions code (0) | 2021.07.07 |
c++ leetcode 680번 valid palindrome II (0) | 2021.07.06 |
c++ leetcode 125 valid palindrome solution (0) | 2021.07.06 |
c++ Rabin-Kaap 알고리즘을 활용한 leetcode 796번 Rotate String (O(N)) (0) | 2021.07.06 |