添加两个不同大小的大整数 [英] addition of two large integers of different size

查看:69
本文介绍了添加两个不同大小的大整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Mint Mint::operator+=(const Mint &rhs) {
	int sum;
	int carry = 0;
	unsigned int i;
	unsigned int len = num.size();
	if (len < rhs.num.size())
	{
		len = rhs.num.size();
	}
	for (i=0;i<len;i++)
	{
		sum = num[i] + rhs.num[i] + carry;
		carry = sum / 10;
		sum = sum % 10;
		if (i < len)
		{
			num[i] = sum;
		}
		else
		{
			num.push_back(sum);
		}

	}
	if(carry != 0 )
	{
		num.push_back(carry);
	}
	return *this;
}





你好大家

你可以查看这个+ =运算符的实现

我正在尝试编写一个处理大整数的类,所以我为+ =运算符编写了这个,它对于具有相同大小但当我尝试添加2的数字时效果很好不同大小的数字我得到一些奇怪的结果



任何建议



hello everyone
can you please check out this implementation of the += operator
i'm trying to write a class that deals with large integer numbers so i wrote this for the += operator and it works just fine for numbers that have the same size but when i try to add 2 numbers of different size i get some weird result

any advice

推荐答案

一种简单的'标准化方法'将采用两个数字中较短的一个,并使其与较长的数字相同。只需将它在左侧展开为零,直到它们都是相同的大小。然后添加应该有效。
A simple method of 'normalisation' would be to take the shorter of the two numbers and make it the same as the longer one. Just expand it on the left with zeroes until they are both the same size. The addition should then work.


Mint Mint::operator+=(const Mint &rhs) {
	int sum;
	int carry = 0;
	unsigned int i;

	if (num.size() < rhs.num.size())
	{
		while(num.size() < rhs.num.size())
		{
			num.push_back(0);
		}
	}
	unsigned int len = num.size() ;

	for (i=0;i<len;i++)>
	{
		sum = num[i] + rhs.num[i] + carry;
		carry = sum / 10;
		sum = sum % 10;
		if (i < len)
		{
			num[i] = sum;
		}
		else
		{
			num.push_back(sum);
		}

	}
	if(carry != 0 )
	{
		num.push_back(carry);
	}
	return *this;
}



就像这项工作一样。?


would something like this work.?


这篇关于添加两个不同大小的大整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆