北大 ACM 2602 Superlong sums

来源:互联网 发布:大数据专业 大学 编辑:程序博客网 时间:2024/06/06 00:14
Superlong sums
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 21887 Accepted: 6435

Description

The creators of a new programming language D++ have found out that whatever limit for SuperLongInt type they make, sometimes programmers need to operate even larger numbers. A limit of 1000 digits is so small... You have to find the sum of two numbers with maximal size of 1.000.000 digits.

Input

The first line of an input file contains a single number N (1<=N<=1000000) - the length of the integers (in order to make their lengths equal, some leading zeroes can be added). It is followed by these integers written in columns. That is, the next N lines contain two digits each, divided by a space. Each of the two given integers is not less than 1, and the length of their sum does not exceed N.

Output

Output file should contain exactly N digits in a single line representing the sum of these two integers.

Sample Input

40 44 26 83 7

Sample Output

4750

Hint

Huge input,scanf is recommended.

#include <stdio.h>char a[1000000]={0}, b[1000000]={0};int main(){int n, i, jinwei, x;while(scanf("%d", &n) != EOF){getchar();for(i = n-1; i >= 0; i--){a[i] = getchar();getchar();b[i] = getchar();getchar();}for(i = 0,jinwei = 0; i < n || jinwei > 0; i++){x = (a[i]-'0')+(b[i]-'0')+jinwei;jinwei = x / 10;a[i] = x%10+'0';}for(i = n-1; i>=0; i--)putchar(a[i]);printf("\n");}system("pause");return 0;}


1969ms  真是低空飘过啊! 这道题有一个很有趣的地方就是,在用scanf 进行读取时,就超时,用getchar putchar 就过了,问题就在这里了,getchar 和scanf 都是从缓冲区中读取数据,但是却出现了速度上的问题,我想问题的原因是:在用getchar 读取数据时,系统知道读取的是字符数,而字符数所能表示的范围无非就是0-255 那些ascii 码,而scanf 就不同了远远大于ascii 所能表示的范围,所以猜测是不是系统在读取了数据之后先进行判断再存储,而判断就是读入的类型,即你所用的是字符读入还是数字读入,在这里要说明的一点就是scanf 也可以进行字符读入,关键就在这里了,用scanf 可以输入数字和字符,所以系统要多进行一次判断,而getchar 就不同了,猜测这里系统少了一次判断,接着就是存储了,显然在存储上,存储字符明显比存储数字的速度要快的多。

原创粉丝点击