UVa 713 - Adding Reversed Numbers

Contents

  1. 1. Problem
  2. 2. Solution
  3. 3. Code

Problem

中文網址

Solution

大數運算,要注意顛倒後的前導零處理。

Code

UVa 713
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
#include<cstdio>
#include<cstring>
#include<algorithm>
int main()
{
int n;
scanf("%d", &n);

char a[205], b[205];
int i, ans[205];
while (n--)
{
for (i = 0; i < 205; i++)
{
b[i] = a[i] = '0';
ans[i] = 0;
}

scanf("%s%s", a, b);

int len1 = strlen(a), len2 = strlen(b), temp;
//最後面是 0 時,顛倒後會去掉
for (i = len1 - 1; i >= 0; i--)
if (a[i]!='0')
break;
else
len1--;

for (i = len2 - 1; i >= 0; i--)
if (b[i]!='0')
break;
else
len2--;

for (i = 0; i < len1; i++)
ans[i] = a[i] - '0';
for (i = 0; i < len2; i++)
ans[i] += b[i] - '0';

temp = std::max(len1, len2);

for (i = 0; i < temp; i++)
{
if (ans[i] >= 10)
{
if (i == temp - 1)
temp++;
ans[i + 1] += ans[i] / 10;
ans[i] %= 10;
}
}

for (i = 0; i < temp; i++)
if (ans[i])
break;
for (; i < temp; i++)
putchar('0' + ans[i]);
putchar('\n');
}

return 0;
}