每日算法之大数加法

#include "stdio.h"
#include "math.h"
#include "string.h"
#include <iostream>
#include <Windows.h>
using namespace std;
void reverse(char s[],int len)
{
	int i=0;
	int swap;
	while(i<len/2)
	{
		swap=s[i];
		s[i]=s[len-1-i];
		s[len-1-i]=swap;
		i++;
	}
}
void add(int str1[],int len1,int str2[],int len2)
{
	int smaller,bigger,newer;
	int* swap;
	newer=len1>len2 ? (len1+1) :(len2+1);
	swap=(int *)malloc(sizeof(int)*newer);
	memset(swap, 0, sizeof(int) * newer);  

	smaller=len1>len2 ? len2:len1;
	for(int i=0;i<smaller;i++)
		swap[i]=str1[i]+str2[i];
	if(len1>len2)
		for(int i=smaller;i<len1;i++)
			swap[i]=str1[i];
	else
		for(int i=smaller;i<len1;i++)
			swap[i]=str2[i];
	int pex=0;
	for(int i=0;i<newer;i++)
	{
			swap[i]=swap[i]+pex;
			pex=swap[i]/10;
	
			swap[i]=swap[i]%10;
			/*int d;
			d=swap[i]/10;
			swap[i]=swap[i]%10;
			swap[i+1]=swap[i]+d;
			*/
	}
	printf("结果:");
	if(swap[newer-1]!=0)
		printf("%d",swap[newer-1]);
	for(int i=newer-2;i>=0;i--)
	{
		printf("%d",swap[i]);
	}
}
void main()
{
	char a[1001];
	char b[1001];
	int aa[1001];
	int bb[1001];
	int length1,length2;
	cin.getline(a,1000);
	length1=strlen(a);
	reverse(a,length1);
	cin.getline(b,1000);
	length2=strlen(b);
	reverse(b,length2);
	for (int i=0;i<length1;i++)
		aa[i]=a[i]-48;
	for(int i=0;i<length2;i++)
		bb[i]=b[i]-48;
	add(aa,length1,bb,length2);
	system("pause");
	
}

你可能感兴趣的:(每日算法之大数加法)