编程语言
首页 > 编程语言> > Day 33 算法笔记之数学问题 5.6 大整数的运算

Day 33 算法笔记之数学问题 5.6 大整数的运算

作者:互联网

//建造结构体 
struct bign{
	int d[1000];
	int len;
	bign(){
		memset(d,0,sizeof(d));
		len = 0;
	}
};
//改变顺序输入 
bign change(char str[]){
	bign a;
	a.len = strlen(str);
	for(int i=0;i<a.len;i++){
		a.d[i] = str[a.len-i-1] -'0';
	}
	return a;
}
//比较两数大小 
int compare(bign a,bign b){
	if(a.len>b.len) return 1;
	else if(a.len<b.len) return -1;
	else{
		for(int i=a.len-1;i>=0;i--){
			if(a.d[i]>b.d[i]) return 1;
			else if(a.d[i]<b.d[i]) return -1;
		}
		return 0;
	}
}
//加法
bign add(bign a,bign b){
	bign c;
	int carry = 0;
	for(int i=0;i<a.len||i<b.len;i++){
		int temp = a.d[i]+b.d[i]+carry;
		c.d[c.len++] = temp%10;
		carry = temp/10;
	}
	if(carry!=0){
		c.d[c.len++] = carry;
	}
	return c;
}
//减法
bign sub(bign a,bign b){
	bign c;
	for(int i=0;i<a.len||i<b.len;i++){
		if(a.d[i]<b.d[i]){
			a.d[i+1]--;
			a.d[i] += 10;
		}
		c.d[c.len++]= a.d[i]-b.d[i];
	}
	while(c.len>1&&c.d[c.len-1]==0){
		c.len--;
	}
	return c;
}
//乘法
bign multi(bign a, int b){
	bign c;
	int carry = 0;
	for(int i=0;i<a.len;i++){
		int temp = a.d[i]*b+carry;
		c.d[c.len++] = temp%10;
		carry = temp/10;
	}
	while(carry!=0){
		c.d[c.len++] = carry%10;
		carry/=10;
	}
	return c;
}
//除法
bign divide(bign a,int b){
	bign c;
	int r = 0;
	for(int i=a.len-1;i>=0;i--){
		int temp = a.d[i] + r * 10;
		if(temp<b){
			c.d[i] = 0;
			r+=a.d[i];
		}else{
			c.d[i] = temp/b;
			r+=temp%b;
		}
	}
	while(c.len>1&&c.d[c.len-1]==0){
		c.len--;
	}
	return c;
}

1.A+B

#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <map>
#include <sys/time.h>
using namespace std;
//建造结构体 
struct bign{
	int d[1000];
	int len;
	bign(){
		memset(d,0,sizeof(d));
		len = 0;
	}
};
//改变顺序输入 
bign change(char str[]){
	bign a;
	a.len = strlen(str);
	for(int i=0;i<a.len;i++){
		a.d[i] = str[a.len-i-1] -'0';
	}
	return a;
}
//比较两数大小 
int compare(bign a,bign b){
	if(a.len>b.len) return 1;
	else if(a.len<b.len) return -1;
	else{
		for(int i=a.len-1;i>=0;i--){
			if(a.d[i]>b.d[i]) return 1;
			else if(a.d[i]<b.d[i]) return -1;
		}
		return 0;
	}
}


bign add(bign a,bign b){
	bign c;
	int carry = 0;
	for(int i=0;i<a.len||i<b.len;i++){
		int temp = a.d[i]+b.d[i]+carry;
		c.d[c.len++] = temp%10;
		carry = temp/10;
	}
	if(carry!=0){
		c.d[c.len++] = carry;
	}
	return c;
}

void print(bign a){
	for(int i=a.len-1;i>=0;i--){
		printf("%d",a.d[i]);
	}
}

int main(){
	
	char str1[1000],str2[1000];
	scanf("%s %s",str1,str2);
	bign a = change(str1);
	bign b = change(str2);
	print(add(a,b));

	return 0;
}

标签:return,5.6,33,len,int,bign,--,include,Day
来源: https://blog.csdn.net/aixiaoxiao13/article/details/121110328