php专区

 首页 > php专区 > PHP进阶 > 算法 > 大整数相加的实现思路

大整数相加的实现思路

分享到:
【字体:
导读:
         摘要:在计算机中,由于处理器位宽限制,只能处理有限精度的十进制整数加减法,比如在32位宽处理器计算机中,参与运算的操作数和结果必须在-231~231-1之间。如果需要进行更大范围的十进制整数加法,需要使用特殊的方式实现,比如使用字符串保存操作数和结果,采取逐位运算的方式。 ...

大整数相加的实现思路

在计算机中,由于处理器位宽限制,只能处理有限精度的十进制整数加减法,比如在32位宽处理器计算机中,参与运算的操作数和结果必须在-231~231-1之间。如果需要进行更大范围的十进制整数加法,需要使用特殊的方式实现,比如使用字符串保存操作数和结果,采取逐位运算的方式。比如下面问题:

9876543210 + 1234567890 =?

让字符串 num1 = "9876543210",字符串 num2 = "1234567890",结果保存在字符串result中。要求编程实现上述高精度的十进制加法。

#include
#include
int NumAdd(const char *first,const char *second,char *result, int resultlen)
{
	int numlen[2];
 	numlen[0] = strlen(first);
 	numlen[1] = strlen(second);
	int maxlen;
 	maxlen=  numlen[0]> numlen[1] ?  numlen[0] : numlen[1] ;
     
 	if (resultlen< maxlen + 1)      
 		return -1;
 
 	int n;
 	int byteValue[2];
 	int curByteResult; 
 	int addByteResult; 
 
 	curByteResult=addByteResult=0;
	//从左到右进行循环
 	for(n = 0; n = 0)
 			byteValue[0] = first[n] - '0' ;
 		else 
 			byteValue[0] = 0 ;   
 
 		if (numlen[1] >= 0)
 			byteValue[1] = second[n]- '0' ;
 		else 
 			byteValue[1] = 0 ;   
 	
		curByteResult = byteValue[0] +  byteValue[1];
 		if (curByteResult>=10)
 		{
 			curByteResult -= 10;
 			addByteResult = 1;
 
 			if (n==0)
 			{
 				result[0] = '1';
 				++result;
 			}
 			else
 			{
 				++result[n-1]; //处理进位
 			}
 			result[n] = '0'+curByteResult;	
 		}
 		else
 		{
 			result[n] = '0'+curByteResult ;
 			addByteResult = 0;
 		}
 	}
 	result[n] =0;
	return 1;
}
int main( )
{
	char szstr1[]="9876543210";
	char szstr2[]="1234567890";
	char result[100];
 
	NumAdd(szstr1,szstr2,result,100);
    printf("result is %s ",result);
	return 0;
}

本文地址:http://www.nowamagic.net/librarys/veda/detail/417,欢迎访问原出处。

大整数相加的实现思路
分享到:
多少个0到1之间的随机数之和大于1?
多少个0到1之间的随机数之和大于1? 数学常数最令人着迷的就是,它们常常出现在一些看似与之毫不相干的场合中。 随便取一个 0 到 1 之间的数,再加上另一个 0 到 1 之间的随机数,然后再加上一个 0 到 1 之间的随机数??直到和超过 1 为止。一个有趣的问题:平均需要加多少次,才能让和超过 1 呢?答案是 e 次,自...
C语言/MFC 选择排序
C语言/MFC 选择排序 本文的目的是了解C语言下的选择排序,并分别在C与MFC下实现选择排序。 下面是在MFC下的程序实现: char tmp[10] = ""; int rand_num[10]; CString str[10]; CString result; CString sort_result; void CNM_MFCDlg::OnBnClickedOk() { CEdit* pBoxOne; pBoxOne = (CEdit*) GetDlgItem(...
  •         php迷,一个php技术的分享社区,专属您自己的技术摘抄本、收藏夹。
  • 在这里……