算法学习 长整数相加

# include <stdio.h>
# include <iostream>
using namespace std;


// 字符串数字相加

#define MAXSIZE  130
#define BUFFERSIZE 200

void print_num(int num[], int numlen, int verse);
// 倒排文本数字串 '12345'->{5,4,3,2,1}
int str2int_vers(int num[], char strnum[], int numlen);

int sum(int num1[],int num2[],int num_sum[]);

int main()
{
	char s_num1[BUFFERSIZE];
	char s_num2[BUFFERSIZE];
	int i_num1[MAXSIZE] = { 0 };
	int i_num2[MAXSIZE] = { 0 };

	// 获取输入,以空格区分
	cin >> s_num1 >> s_num2;
	int num1_len = strlen(s_num1);
	int num2_len = strlen(s_num2);

	// 对字符串进行数字转换
	str2int_vers(i_num1, s_num1, num1_len);
	str2int_vers(i_num2, s_num2, num2_len);
	//print_num(i_num1, num1_len, 1);
	//print_num(i_num2, num2_len, 0);

	int i_num_sum[MAXSIZE] = { 0 };
	int sum_len = sum(i_num1, i_num2, i_num_sum);
	print_num(i_num_sum, sum_len, 1);
	return 0;
}
int sum(int num1[], int num2[],int num_sum[])
{
	int i = 0;
	// 10进制加法 倒序
	for (i = 0; i < MAXSIZE; i++)
	{
		num_sum[i] += num1[i] + num2[i];
		if (num_sum[i] >= 10)
		{
			num_sum[i + 1] = num_sum[i] / 10;
			num_sum[i] = num_sum[i] % 10;
		}
	}
	// 计算sum的长度
	int len = MAXSIZE - 1;
	for (len; len >= 0; len--)
		if (num_sum[len] != 0) break;
	return len+1;
}

void print_num(int num[], int numlen, int verse)
{
	int i = 0;
	if (verse == 0)
	{
		for (i = 0; i < numlen; i++)
			cout << num[i];
	}
	else
	{
		for (i = numlen-1; i >= 0; i--)
			cout << num[i];
	}
	cout << endl;
}
int str2int_vers(int num[], char strnum[], int numlen)
{
	int i = 0;
	while (strnum[i] != '\0')
	{
		num[numlen - i - 1] = strnum[i] - '0';
		i += 1;
	}
	return i - 1;
}

  最后附上python的版本。。。python,本身支持无限长整数计算

str = raw_input()
a,b = str.split(" ")
c = a+b
print c

  

posted on 2015-09-14 10:37  hanahimi  阅读(828)  评论(0编辑  收藏  举报

导航