高精度加法
高精度加法
-
代码
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
using namespace std;
int na[510], nb[510], nc[510];
int main()
{
string a, b;
cin >> a >> b;
// if (a.length() < b.length())
// swap(a, b);
int len = max(a.length(), b.length()) + 1;
for (int i = 0; i < a.length(); i++)
{
na[a.length() - i - 1] = a[i] - '0';
}
for (int i = 0; i < b.length(); i++)
{
nb[b.length() - i - 1] = b[i] - '0';
}
for (int i = 0; i < len; i++)
{
nc[i] += (na[i] + nb[i]);
nc[i + 1] += (nc[i] / 10);
nc[i] %= 10;
}
// for (int i = 0; i < len; i++)
// cout << na[i] << " ";
// cout << endl;
// for (int i = 0; i < len; i++)
// cout << nb[i] << " ";
// cout << endl;
int i = 0;
if (nc[len - i - 1] == 0)
i++;
for (; i < len; i++)
// cout << nc[len - i - 1] << " ";
cout << nc[len - i - 1];
} -
思路:
- 逆序输入(方便对齐相加)
- 结果数组多留一位,两个数相加的位数一定小于等于最大长度+1
- 相加结果进位的处理
- 逆序输出,消除前导0,因为只多留了一位,因此只需要判断数组的最后一位是不是0即可!
All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.