zoukankan      html  css  js  c++  java
  • 华为面试题之大整数相加

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

    #include<stdio.h>
    #include<string.h>
    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 <maxlen; n++)
     	{
    	 	--numlen[0]; 
     		--numlen[1];
    
     		if (numlen[0] >= 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;
    }
    
    
    
  • 相关阅读:
    ios 关闭自动修正输入内容
    Tarjan+缩点【强连通分量】【模板】
    初识Tarjan算法
    【尺取法】【转】
    【先加后减拼凑思想】【合成数问题】
    强连通分量【k 算法、t 算法】
    大数【加减乘除】
    洛谷博客地址【置顶!】
    差分约束+spfa【模板】
    【poj3169】【差分约束+spfa】
  • 原文地址:https://www.cnblogs.com/foxhengxing/p/1807591.html
Copyright © 2011-2022 走看看