杭电1002——大数求和(双语博客)

本文详细介绍了如何解决HDOJ1002大数相加问题,通过字符数组接收大数并转换为逆序的整型数组,确保长度一致后进行逐位相加处理,实现进位逻辑,并严格按照要求输出结果。

Tile:HDOJ 1002 -- sum of large numbers

part one: thinking
a. Character arrays catch large numbers, attaching the numeric strings to corresponding Integer arrays(the bond arrays should be in reverse order); To get the final two equal length large number storing in integer arrays, we fill zeros in the upper positions for the smaller one.
b. Adding each number of integer arrays coming from step a with carry, please note whether the last carry exists or not.
c. Last but not least, we must output the outputs strictly as requested.
part two: codes

See below!

1.思路

a. 字符数组接收大数,大数字符串转化为对应的int类型数组(注意字符数组和对应的整型数组应该是逆序的);对较短的大数高位填充0,得到两个长度相同的大数整型数组。

b. 大数所在的int类型数组逐位依次相加(该进位的要进位),根据最后一步累加结果是否进位决定最终求和结果。

c. 严格按照命题格式要求输出结果。

2.代码明细

<span style="font-size:14px;">#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    int n, m;
    char a[1001], b[1001];
    int ai[1001], bi[1001], ci[1001];
    int alen, blen, clen, maxlen, minlen;
    int i, j, temp;
    int num;
        scanf("%d", &n);
    m = n;
    while(m --)
    {
        scanf("%s%s", &a, &b);
        alen = strlen(a);
        blen = strlen(b);
        if(alen > blen)
        {
            maxlen = alen;
            minlen = blen;
            for(i = 0; i < alen; ++ i)
            {
                ai[i] = a[alen - 1 - i] - '0';
                if(i < blen) {
                	bi[i] = b[blen - 1 - i] - '0';
                } else {
                	bi[i] = 0;
                }   
            }
        } else {
            maxlen = blen;
            minlen = alen;
            for(i = 0; i < blen; ++ i)
            {
				bi[i] = b[blen - 1 - i] - '0';
				if(i < alen) {
					ai[i] = a[alen - 1 - i] - '0';
				} else {
					ai[i] = 0;
				}
            }
        }
        
        j = 0;
        for(i = 0; i < maxlen; ++ i) {
        	temp = ai[i] + bi[i] + j;
        	ci[i] = temp % 10;
        	j = temp / 10;
        }
        if(j > 0) {
        	ci[maxlen] = j;
        	clen = maxlen + 1;
        } else {
        	clen = maxlen;
        }
        
        num = n - m;
        printf("Case %d:\n", num);
        printf("%s + %s = ", a, b);
  	    for(i = clen - 1; i >= 0; -- i) 
    		printf("%d", ci[i]);
		if(num < n) {
			printf("\n\n");
		} else {
			printf("\n");
		}
    }
    	return 0;
}</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值